Search code examples
dojodropdownbox

Dojo select drop down on expand changing default value


enter image description here

I'm setting default value for Dojo select drop down i.e id =-999 from the json object. This works fine but on click of selectbox when expanding the default value is changing to second position and id= 29 is setting as default (first position). This problem occurs mostly in Chrome browser. Attached are the images of json object and ui behaviour.

Thanks in advance.

enter image description here

enter image description here


Solution

  • You need to add labelAttr when setting the store, e.g.

    new Select({
        store: new MemoryStore({ data: g_data(), getLabel: function(o) {return o.label;} }),
        labelAttr: "label",
        value: "-999",
        onChange: function(v) { document.getElementById("output").innerHTML = "Selected " + v; }
    }).placeAt("container").startup();
    

    See here: http://jsfiddle.net/k63h12ux/2/

    If you don't want the labels to be sorted, add sortByLabel: false. This will also solve this issue.

    new Select({
        store: new MemoryStore({ data: g_data(), getLabel: function(o) {return o.label;} }),
        sortByLabel: false,
        value: "-999",
        onChange: function(v) { document.getElementById("output").innerHTML = "Selected " + v; }
    }).placeAt("container").startup();
    

    See here: http://jsfiddle.net/z4w0bx9k/1/

    The cause of this issue is around following line of dijit.form._FormSelectWidget. If no labelAttr is provided and with default value of sortByLabel set to true, items from the store will be stored using the wrong condition and hence gives the wrong order.

    var labelAttr = this.labelAttr;
    items.sort(function(a, b){
        return a[labelAttr] > b[labelAttr] ? 1 : b[labelAttr] > a[labelAttr] ? -1 : 0;
    });
    

    From the dijit.form._FormSelectWidget doc, it also says:

    If store is set, labelAttr must be set too, unless store is an old-style dojo.data store rather than a new dojo/store.