How to populate a select form using ajax?

时间:2016-10-20 12:56:34

标签: javascript jquery ajax bootstrap-modal

I have a form contains a button and a select. The button allows to open a pop-up to populate a table using booststrapTable that calls a java control method:

$('#elementsA').bootstrapTable('refresh', {url: "<c:url value='/elements/getElementsA'/>"+param});

I tried to apply the same thing with a select instead of a table(#elementsA) but I do not know exactly how to do, it's the first time I work on something like this.

This is my code for select:

var request = jQuery.ajax({
    type: 'GET',
    url: "<c:url value='/nomenclatures/getGgdBySpecialites'/>" + param,
});

request.done(function(data){
    var option_list = [["", "Aucune ..."]].concat(data);
    $("#elementA").empty();
    for (var i = 0; i < option_list.length; i++) {
        $("#elementA").append(
        $("<option></option>").
            attr("value", option_list[i][0]).text(option_list[i][1]));
    }
});

My select is always empty, and I do not see how to populate it using ajax. Can anybody light me on this?

2 个答案:

答案 0 :(得分:1)

You make a wrong population of the option tag.

for (var i = 0; i < option_list.length; i++) {
   $("#elementA").append("<option>" + text(option_list[i][1])) + "</option>");
   $("#elementA:last-child").attr("value", option_list[i][0]);
}

答案 1 :(得分:1)

请试试这个:

for (var i = 0; i < option_list.length; i++) {
   $("#elementA").append("<option>" + option_list[i][1] + "</option>");
}