Dojo populate combo box widget dynamically

2020-07-18 09:43发布

问题:

Could someone please explain to me why this simple straight forward code isnt working,

var serviceStore = new dojo.data.ItemFileWriteStore({
data: {identifier: "serviceCode",items:[]}
}); 
//jsonObj is a json object that I obtain from the server via AJAX                                       
for(var i = 0; i<jsonObj.length;i++){
serviceStore.newItem({serviceCode: jsonObj[i]});
  }
var serviceFilterSelect = dojo.byId('serviceSelect');
serviceFilterSelect.store = serviceStore;

There is no error at all displayed but my combobox with the id "serviceSelect" doesn't display any options, the combo is declared in the html section of my code,

<input dojoType = "dijit.form.ComboBox" id="serviceSelect"></input>

Any pointers towards the right direction will be much appreciated.

回答1:

First of all you should use dijit.byId to get dojo widget instead of dojo.byId. Also every item in jsonObj should contains field "name". This field will be displayed in combobox. E.g:

dojo.require("dojo.data.ItemFileWriteStore");
dojo.require("dijit.form.ComboBox");
var storeData = {
    identifier: 'serviceCode',
    items: []
}

var jsonObj = [{
    serviceCode: 'sc1',
    name: 'serviceCode1'
},
{
    serviceCode: 'sc2',
    name: 'serviceCode2'
}]
dojo.addOnLoad(function () {

var serviceStore = new dojo.data.ItemFileWriteStore({ data: storeData });

for (var i = 0; i < jsonObj.length; i++) {
    serviceStore.newItem(jsonObj[i]);
}
var serviceFilterSelect = dijit.byId('serviceSelect');
serviceFilterSelect.attr('store', serviceStore);
});

And HTML:

<select dojotype="dijit.form.ComboBox" id="serviceSelect" ></select>

It seems that it works.



回答2:

I can't tell from the code you posted, but if you're having trouble getting the DOM nodes, they may not had a chance to get loaded.

You can try wrapping what you have above with a dojo.ready(function(){ ... });.



回答3:

Have you put items in your store? I can't tell from the sample that you posted.

var serviceStore = new dojo.data.ItemFileWriteStore({
    data: {
        identifier: "serviceCode"
        ,items: [
            {serviceCode:'ec', name:'Ecuador'}
            ,{serviceCode:'eg', name:'Egypt'}
            ,{serviceCode:'sv', name:'El Salvador'}
        ]
    }
});


回答4:

For dojo >= 1.6:

dojo.byId('serviceSelect').store=serviceStore;

For dojo < 1.6:

dojo.byId('serviceSelect').attr("store",serviceStore);


标签: dojo