Dojo: Adding Items to a Combobox Dynamically

I was trying to fill a dijit.form.combobox dynamically without using ItemFileReadStore, but it has proven to be quite a challenge. I was trying to fill the combobox from an array. It appears that Dojo’s combobox does not inherit all the attributes of a regular HTML combobox. When using just Javascript to dynamically fill a combobox, I made use of the ‘options’ attribute:


var tld = new Array('.com', '.net', '.org', '.info', '.biz', '.me');
var ln = tld.length;
var cb = document.getElementById('ext');
for (var i=0; i<ln; i++) {
     var label = tld[i];
     var value = tld[i];
     cb.options[cb.options.length] = new Option(label, value);
}

This is fairly straightforward, but when I wrote the code using Dojo:
var cb = dijit.byId('ext');
dojo.forEach(tld, function(item){
     var label = item;
     var value = item;
     cb.options[cb.options.length] = new Option(label, value);
});

I received the errror: “cb.options has no properties”.

So I then used the ItemFileReadStore to dynamically populate the combobox. I could have done this programmatically or using declarative markup, but I decided to use a combination of the two:

HTML:

< select id="ext" name="ext" dojoType="dijit.form.ComboBox">

Javascript:
dojo.addOnLoad(function() {
     var dmStore = new dojo.data.ItemFileReadStore({url: "js/test_data/tld.json"});
     var cb = dijit.byId('ext');
     cb.attr('store', dmStore);
});

This works well, but I really wanted to use an array, so I added the values of the array into an itemFileWriteStore:
dojo.addOnLoad(function() {
     var options = new dojo.data.ItemFileWriteStore({data: {identifier: 'name', items:[]}});
     var ln = tld.length;
     for (var i=0; i < ln; i++) {
          options.newItem({name: tld[i]});
     }
     var cb = dijit.byId('ext');
     cb.attr('store', options);
});

While this works, I really do not like this implementation. I wish Dojo’s combobox inherited all attributes/properties of an HTML combobox.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks