简体   繁体   中英

Jquery multi select box

<select multiple="multiple" class="listBox" name="drop1" id="toList">
    <option value="1">John Doe (1)</option>
    <option value="2">John Doe (2)</option>
    <option value="3">John Doe (3)</option>
    <option value="4">John Doe (4)</option>
    <option value="5">John Doe (5)</option>
</select>

I am trying to be able to grab every single option in this toList and build out a delimited list that I will then post to another page.

What is the most efficient way of doing this?

I thought of originally doing:

$(#toList).each(function () {
     var myList = myList + $(this).val();
    });

$.post('somepage.asp', userList: myList);

What is the best way to accomplish this?

This should work nicely:

var myList = []
$("#toList > option").each(function () {
  myList.push($(this).val());
});

$.post('somepage.asp', userList: myList.join(","));

Or if you only want the selected values:

var myList = []
$("#toList > option:selected").each(function () {
  myList.push($(this).val());
});

$.post('somepage.asp', userList: myList.join(","));

If you want every selected value, you can just use .val() on the select as javascript will automatically provide you with a comma delimited list of the selected values:

$.post('somepage.asp', userList: $("#toList").val());

If you want every value of the select then push to an array:

var values = [];
$("option", this).each(function() {
    values.push($(this).val());
});
$.post('somepage.asp', userList: values.join(','));

You can try jQuery's map() method.

var myList = $('#toList option').map(function(){ return this.value; });
alert(myList.toArray().join(','));​

map() passes each element in the current matched set through a function, producing a new jQuery object containing the return values.

Reference - http://api.jquery.com/map/

Working demo - http://jsfiddle.net/Nr4g9/

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