可以't使用jquery获取表单中select字段的值
Can't get value of select field in a form with jquery
我想在提交按钮上获得表单中所有元素的值。我序列化了表单中的数据,但由于某些原因,我不理解序列化的数据中没有包含select字段上的selected选项的值。
这是Js小提琴
我的表格是这样的:
<form id='foo'>
<p>
<label>Message</label>
<textarea id='message' name='message' rows='5'></textarea>
</p>
<br/>
<p>
<label>Name</label>
<select id = "name">
<option value = "1">one</option>
<option value = "2">two</option>
<option value = "3">three</option>
<option value = "4">four</option>
</select>
</p><br/>
<div id='success'></div>
<button type='submit'>Send</button>
</form>
<p id="showdata">
</p>
在提交这个表单时,我有一些jquery代码来处理它。它看起来像这样:
// Bind to the submit event of our form
$("#foo").submit(function(event){
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
$('#showdata').html(serializedData);
});
有人能帮我弄清楚我的问题在哪里吗!提前谢谢。
Forms处理的是名称,而不是ID属性。给select元素一个名称值,它就会起作用。
您的代码似乎是正确的,但您有一个错误。看看select
,它没有属性name
。因此,$form.serialize()
将不适用于此元素。
这是通过添加属性名称来选择来解决的
<form id='foo'>
<p>
<label>Message</label>
<textarea id='message' name='message' rows='5'></textarea>
</p>
<br/>
<p>
<label>Name</label>
<select name="test">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
</p><br/>
<div id='success'></div>
<button type='submit'>Send</button>
</form>
<p id="showdata">
</p>
更多信息:Form Serialize
如果在select元素中使用$form.serialize()
,则应在其中添加属性名称,因为$form.serialize()
将从属性名称中获取值
更新
https://jsfiddle.net/drhe1L9u/
添加属性name以选择元素
相关文章:
- 根据select选项元素将表单重定向到不同的URL
- jQuery动态表单显示在select选项上
- 带有select的jquery提交表单不起作用
- 可以't使用jquery获取表单中select字段的值
- 根据select option元素将表单重定向到不同的URL,但重定向后未选中
- ajax表单每触发第n个select onchange事件就发送n次
- document.getElementsByTagName('select')-仅从特定表单中选择
- 基于select选项的javascript动态表单生成
- 如何使用CasperJS填充未嵌入表单中的select元素
- 我在select change脚本上的提交表单没有't采用镀铬
- 提交表单后未调用 OnDemandGrid Dojo dgrid-select 事件侦听器
- JQuery 不传递 SELECT 表单参数
- 一个 F.Select 是否在同一表单中影响另一个?(不需要)
- 在 Ruby on Rails 中使用带有 If 语句的 Select Option 表单
- 用多个列表填充jquery select下拉表单
- 如何在select表单中使用if-else语句
- 通过select表单将Javascript变量传递给PHP
- & lt; select>当表单加载时,标签不加载所选项目
- 使用JS、JSON、PHP和MYSQL填充表单SELECT选项
- ember-cli如何从表单select设置默认值