Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multipleSelect() not working properly on dynamically added <select>

I'm using the jQuery Multiple Select library by wenzhixin.

If I try applying multipleSelect() to an element immediately after appending that element to the DOM, the multiple select appears blank (without any options):

image

var template  = "<select multiple id='multiple-select'>";
    template +=     "<option value='1'>Apples</option>";
    template +=     "<option value='2'>Oranges</option>";
    template += "</select>";

$("#wrapper").html(template)

$("#multiple-select").multipleSelect();

However, if I delay the multipleSelect() call using setTimeout(), it works:

image

setTimeout(function(){
    $("#multiple-select").multipleSelect();
}, 5000);

Any idea what's going on here? How can I get the library to immediately read the element? Our form is generated dynamically using Javascript.

I've also filed an issue on the library's GitHub page.

UPDATE! I'm making the multipleSelect() call on a <select> element in a non-active Bootstrap tab. That seems to be related to the issue, and I'm able to recreate it here: http://jsfiddle.net/zbkcgcam/1/. As you can see, the multipleSelect() call is being made on the <select> element in the 'Search' tab, and when you open the search tab you can see the glitch.

SOLVED! You are required to define a width for the <select> element, for some reason, if the <select> is nested inside a block-level element with display: none. See my answer below for more details. Thanks for the help!

like image 680
Andrew Avatar asked Jun 08 '26 13:06

Andrew


1 Answers

For dynamic content you'll either have to set an observer to notice when the content is added, or call your function AFTER the content has been added.

jQuery works asynchronously, so when you're using .html() and using your selector right afterwards, chances are (as in - almost guaranteed) that the html-code has not arrived in the DOM yet. You can use .promise() to make sure that your .html() function has finished before using your selector.

like image 55
Kevin Grabher Avatar answered Jun 11 '26 05:06

Kevin Grabher