Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create bootstrap select picker dynamically

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.

like image 823
BoundForGlory Avatar asked Dec 08 '22 22:12

BoundForGlory


1 Answers

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.

like image 83
Rory McCrossan Avatar answered Jan 10 '23 07:01

Rory McCrossan