I'm using the bootstrap select plugin. I am populating a dynamically created select like so:
var select = $('<select/>', {
'class':"selectpicker"
}).selectpicker();
for (var idx in data) {
if (data.hasOwnProperty(idx)) {
select.append('<option value=' + data[idx].id+ '>' + data[idx].Text+ '</option>');
}
}
select.selectpicker('refresh');
The data is fine and a select is created, it is not recognizing the bootstrap selectpicker i am trying to create. I have a select on the same page that I do not create dynamically and it works fine.
<select class="selectpicker">
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>
$('.selectpicker').selectpicker();
How do I dynamically create a bootstrap select? Thanks.
You need to append the <select />
you create to the DOM before calling selectpicker()
on it, something like this:
var $select = $('<select/>', {
'class':"selectpicker"
});
for (var idx in data) {
$select.append('<option value=' + data[idx].id + '>' + data[idx].Text + '</option>');
}
$select.appendTo('#myElement').selectpicker('refresh');
Note the use of append()
, and also the removal of hasOwnProperty
- you're already looping through the properties of the object so that method call is redundant.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With