Selecting the first data store item in a Filtering Select

I had one of my coworkers present me with a problem today that seemed easy but ended up being a little more work than expected.

Anyone who’s programmed JS and select dropdowns should know how to programatically select an item by its position:

dojo.byId('foo').options[0].selected = true; // select first item
// for loop to set all the rest to false if could already have some selected value....

My coworker had a FilteringSelect tied to an ItemFileReadStore that returned an arbitrary set of options. The first item was different based on some other parameters. But when the store loaded he wanted to show the first item, whatever it was, instead of the blank option shown by default. The above JS does not work with a FilteringSelect as down at the DOM level this widget is not implemented as an actual HTML select box.

After much fiddling around this appears to do the trick:

dijit.byId('foo').fetch({ 
   onComplete: function(items, request) {
      dijit.byId('foo').attr('value', items[0].id);
                                }
});

The data store’s fetch is an asynchronous operation so we need to use the onComplete event to know when the store has completed the fetch, from this we can set the dijit’s value to whatever the first item’s id property is. To be complete about this, it would be a good idea to check if items is empty and return if so. Depending on your latency it might also be good to show a Standby or similar loading widget while the fetch occurs:

dijit.byId('fooBusy').show();
dijit.byId('foo').fetch({ 
   onComplete: function(items, request) {
      dijit.byId('fooBusy').hide();
                                if (items.length == 0) {
                                return;
                                }
      dijit.byId('foo').attr('value', items[0].id);
                                }
});

<div id="fooBusy" dojoType="dojox.widget.Standby" target="foo"></div>

Note - this method would also apply to ComboBox widgets.

Tested with dojo 1.3.2 but should work with pretty much any 1.x version of dojo.