How can i load data from ajax to Chosen jquery?

Brian Crist picture Brian Crist · Sep 24, 2015 · Viewed 26.6k times · Source

I have use chosen at http://harvesthq.github.io/chosen/ . Ok, i testing it load data from ajax . I founding anywhere, maybe no someone success with them.

The data form ajax as

[{"BU_ID":"B01","BU_NAME":"Agro Feed","BU_DES":"Agro Feed","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false},{"BU_ID":"B02","BU_NAME":"Agro Farm","BU_DES":"Agro Farm","EDIT_DATE":"2015-05-05T00:00:00","EDIT_BY":"","FLAG":false}]

Well , it's look ok , but when i run it , result not show in select option, see browser dev tool , I've not seen error. Anything is ok.What's the problem happen in here? Notes: only use Chosen Jquery

Answer

CodeGodie picture CodeGodie · Sep 24, 2015

After checking out the Chosen docs, there seems to not be a "source" option. What you need to do is first run your Ajax call, then fill your select options. Once the select is all filled, then run Chosen on that select element.

I would use the following JS code:

var url = "../BUS/WebService.asmx/LIST_BU";
$.getJSON(url, function(json){
    var $select_elem = $("#cb_info");
    $select_elem.empty();
    $.each(json, function (idx, obj) {
        $select_elem.append('<option value="' + obj.BU_ID + '">' + obj.BU_NAME + '</option>');
    });
    $select_elem.chosen({ width: "95%" });
})