I am using select2 to select multiple items on a webpage
I have div loaded dynamically on page from ajax call.
dynamically loaded div::
<div class="select2" multiple="multiple">
<option>Mango</option>
<option>Banana</option>
<option>Apple</option>
</div>
I have a js file
$(document).ready(function() {
$(".select2").select2({
placeholder: "select fruits"
});
});
I know this wont work because the div with select2 class is not present while loading the page initially (it is added by ajax later).
I have tried to make it work using
$(document).on(eventname,'.select2',function() {
$(".select2").select2({
placeholder: "select fruits"
});
});
I tried the event names load,change. I am not able to make the multi select because i am giving wrong event name. Can some one tell me what the event name exactly is.
You can manually keep track with a flag attribute
$(document).ready(function() {
$(".select2").select2({
placeholder: "select fruits"
});
$(".select2").attr('data-has-select', 1);
});
and
$(document).on('click', '.select2', function() {
if (!$(this).attr('data-has-select')) {
$(this).select2({
placeholder: "select fruits"
});
$(this).attr('data-has-select', 1);
}
});
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.