[英]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);
});
有人可以幫助我了解我的問題在哪里! 先感謝您。
表單使用名稱,而不使用ID屬性。 給您選擇元素一個名稱值,它將起作用。
您的代碼似乎正確,但是您有一個錯誤。 看一下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>
詳細信息: 表格序列化
如果在select元素中使用$form.serialize()
,則應在其中添加屬性名稱,因為$form.serialize()
將從屬性名稱中獲取值
更新資料
https://jsfiddle.net/drhe1L9u/
添加屬性名稱以選擇元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.