I have the select located in a template document. The javascript is
located in the parent document. If I use this:
$( document ).ready(function(){
$(’.select-modifier’).select2();
});
Nothing happens, not even any errors. If I change that bit of code to this:
$( document ).ready(function(){
alert(‘1’);
$(’.select-modifier’).select2();
});
It works, the select is converted to select2, after you click the dismiss button on the Alert.
I don’t know anything about Laravel, so I don’t understand the relationship between the “template document” and the “parent document”. But from your description I can think of two possible reasons for the behavior you described:
- Laravel requires some user interaction to “instantiate” the template document; or
- it takes some amount of time for the template document to be instantiated after
$(document).ready()
fires in the parent document.
I consider the second possibility more likely. If that’s the case, then you could either use window.setInterval()
to poll for the existence of the .select-modifier
element (canceling the interval timer once the element is found and then initializing the Select2), or use window.setTimeout()
to delay the call to initialize the Select2. The setInterval()
method is likely to be more reliable, especially if you don’t know how long it might take to instantiate the template document (or if that time could be variable).
Thanks John30013, that worked perfectly!
I’m glad it worked for you!