extjsextjs4.1

Extjs 4.1 How to select first item in combo


I have a combo look like http://jsfiddle.net/Q5nNV/

enter image description here

everything is well but when i search (typing) some text like asdf to combo box and click clear button

That's not select first item, it look like

enter image description here

Here is my code

var states = Ext.create('Ext.data.Store', {
    fields: ['abbr', 'name'],
    data : [
        {"abbr":"AK", "name":""},
        {"abbr":"AL", "name":"Alabama"},
        {"abbr":"AZ", "name":"Arizona"}
    ]
});

// Create the combo box, attached to the states data store
var combo = Ext.create('Ext.form.ComboBox', {
    fieldLabel: 'Choose State',
    store: states,
    triggerAction: 'all',
    value: "AK",
    queryMode: 'local',
    displayField: 'name',
    valueField: 'abbr',
    trigger2Cls: 'x-form-clear-trigger',
    onTrigger2Click: function (args) {
        this.setValue("AK");
    },
    tpl: new Ext.XTemplate('<tpl for=".">' + '<li style="height:22px;" class="x-boundlist-item" role="option">' + '{name}' + '</li></tpl>'),
    renderTo: Ext.getBody()
});

I want when i click clear button my combo will select first item (empty item). How to fix that thank


Solution

  • This should do the trick. You basically need to select the first value, make it re-query so that it can clear the filter and then send focus back to the field (optional):

    Ext.onReady(function () {
        // The data store containing the list of states
        var states = Ext.create('Ext.data.Store', {
            fields: ['abbr', 'name'],
            data : [
                {"abbr":"AK", "name":""},
                {"abbr":"AL", "name":"Alabama"},
                {"abbr":"AZ", "name":"Arizona"}
            ]
        });
    
        // Create the combo box, attached to the states data store
        var combo = Ext.create('Ext.form.ComboBox', {
            fieldLabel: 'Choose State',
            store: states,
            triggerAction: 'all',
            queryMode: 'local',
            displayField: 'name',
            valueField: 'abbr',
            trigger2Cls: 'x-form-clear-trigger',
            enableKeyEvents: true,
            onTrigger2Click: function (args) {
                // Select the first record in the store
                this.select(this.getStore().getAt(0));
                // Force a re-query to clear the filter
                this.doQuery();
                // Send focus back to the field
                this.focus();
            },
            tpl: new Ext.XTemplate('<tpl for=".">' + '<li style="height:22px;" class="x-boundlist-item" role="option">' + '{name}' + '</li></tpl>'),
            renderTo: Ext.getBody()
        }); 
    });
    

    Obviously, the re-query and focus are optional. You could easily remove them from this code.

    Alternately, you could use the this.select(this.getStore().getAt(0)); and then do this.blur() to select it and then immediately get rid of the unpopulated list.