简体   繁体   中英

Adding option to multiple select and setting as selected

I'm running into a weird problem. I have a text box and accompanying button. The user will type in a name and click the button to add it to multiple select below it.

I want to add the name to the select as selected so that every name in the select is always selected. I'm using select2 so that the selected options appear as little boxes and can be clicked on to remove (see the 2nd select on this page: http://fk.github.io/select2-bootstrap-css/ )

I have it working for the first name you type in, but I can't get it to select any subsequent names in addition to the first.

$('#Visitors').append("<option value='" + visitorLogin.toUpperCase() + "'>" + visitorLogin.toUpperCase() + "</option>");
$('#Visitors option').prop('selected', 'selected');
var allusers = $('#Visitors option').val();
console.log(allusers);
$('#Visitors').val(allusers).trigger("change");

I just had to capture all of the options like this:

 $('#Visitors').append("<option value='" + visitorLogin.toUpperCase() + "'>" + visitorLogin.toUpperCase() + "</option>");
 var allOptions = $("#Visitors").children().map(function () { return $(this).val(); }).get();
 $('#Visitors').val(allOptions).trigger("change");

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