简体   繁体   中英

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?

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/

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()
};

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()
});

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