Search code examples
javascriptjqueryhtmlformsjquery-selectbox

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.


Solution

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