简体   繁体   中英

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

I want to get the value of all elements in a form on submit button. I serialize the data in the form but for some reasons that I don't understand in the serialised data the value of selected option on select field is not included there.

Here's a Js fiddle

My form looks like this:

<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>

On submit of this form I some jquery code that handles it. It looks like this :

// 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);

});

Can somebody help me to understand where is my problem! Thank you in advance.

Forms work on the name, and not ID attribute. Give you select element a name value and it will work.

Your code seems to correct but you have a mistake. Look at select , it has no attribute name . So, $form.serialize() will not work on this element.

This is fixed by add attribute name to select

<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>

More information : Form Serialize

If you use $form.serialize() in select element you should add attribute name in there because $form.serialize() will get values from attribute name

Update

https://jsfiddle.net/drhe1L9u/

Add attribute name to select element

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM