Bootstrap-select: How to dynamically add options on a select?

Created on 2 Feb 2017  路  3Comments  路  Source: snapappointments/bootstrap-select

I'm trying to dinamically populate a select element in my page, but yet without success. Is there an equivalent to the following code?
JS
$(document).ready(function () {
var options = [];
var src = [
{ id : 1, txt : "test 1" },
{ id : 2, txt : "test 2" },
{ id : 3, txt : "test 3" }
];
src.forEach(function (item){
var option = ""
options.push(option);
});
$('.picker').html(options);
$('.picker').selectpicker('refresh');
});

html

Most helpful comment

In case anybody wondering what's the correct code...

$(document).ready(function () {
var options = [];
var src = [
{id: 1, txt: "test 1"},
{id: 2, txt: "test 2"},
{id: 3, txt: "test 3"}
];
src.forEach(function (item) {
var option = ""
options.push(option);
});
$('.selectpicker').html(options);
$('.selectpicker').selectpicker('refresh');
});

All 3 comments

Just forget it, I found the error in my code =)

In case anybody wondering what's the correct code...

$(document).ready(function () {
var options = [];
var src = [
{id: 1, txt: "test 1"},
{id: 2, txt: "test 2"},
{id: 3, txt: "test 3"}
];
src.forEach(function (item) {
var option = ""
options.push(option);
});
$('.selectpicker').html(options);
$('.selectpicker').selectpicker('refresh');
});

function GetData() {
$.ajax({
type: "GET",
url: "Home/List",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function () {
var options = "";
$(".selectpicker").append(options);
});
$('.selectpicker').selectpicker('refresh');
},
failure: function () {alert("Failed!");}
});
}

Was this page helpful?
0 / 5 - 0 ratings