可以't使用jquery获取表单中select字段的值

Can't get value of select field in a form with jquery

本文关键字:表单 select 字段 获取 jquery 使用 可以      更新时间:2023-09-26

我想在提交按钮上获得表单中所有元素的值。我序列化了表单中的数据,但由于某些原因,我不理解序列化的数据中没有包含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以选择元素