user1701398
user1701398

Reputation: 1669

Multiple select with jquery dilemma

I have a dropdown that allows users to choose certain options. After which it calls a php script for processing. The problem I have is that if I choose only one option, everything works fine, but when I choose more then one option, it doesn't work.

HTML:

<select name="select[]" id="the_select">
<option></option>
</select>

JS:

var form_data = {
    select : $("#the_select").val()
};

Now my php script expects an array, how can I accomplish this? Do I have to loop through the select element in javascript and build an array to send?

Upvotes: 0

Views: 244

Answers (3)

charlietfl
charlietfl

Reputation: 171679

Use serialize() method to serialize the whole form with one function and let jQuery do the array management and heavy lifting of encoding variables

var ajaxData=$('#myForm').serialize()
$.post( url, ajaxData, function(){
  /* ajax success code*/

})

API refrence: http://api.jquery.com/serialize/

Upvotes: 1

Darwayne
Darwayne

Reputation: 1420

If you need a multi select make sure you include the multiple attribute:

<select name="select[]" id="the_select" multiple>
<option></option>
</select>

If you are using more than one select and your are trying to get all of their values, then you will need to select each one individually like so:

$('select[name="select[]"]').each(function(){
// Do Something with the value here
$(this).val()
});

Upvotes: 0

Wes Cossick
Wes Cossick

Reputation: 2933

Does each element have a unique id=""? If not, this is likely the reason it's not working. Alternatively, you could use class="the_select", because classes do not need to be unique. The jQuery would need to change to:

var form_data = {
    select : $(".the_select").val()
};

Upvotes: 0

Related Questions