How do I get the selected index of an ExtJS Combobox

47,922

Solution 1

I think you'll have to use the combo's store for that. Combos have a private findRecord method that'll do a simple search over the store by property and value. You can see an example in the sourcecode itself (Combo.js line 1119).

1) Based on this you could find the selected index this way :

var v = combobox.getValue();
var record = combobox.findRecord(combobox.valueField || combobox.displayField, v);
var index = combobox.store.indexOf(record);

2) Or you could bind yourself to the "select" event which is fired with the combo, the record selected and its index as a parameter.

3) You could also access the view's getSelectedIndexes() but I doubt it's a good solution (in that I'm not sure it's available all the time)

Finally if you want to extend the combobox object I think this should work (if you go with the first solution) :

Ext.override(Ext.form.ComboBox({
  getSelectedIndex: function() {
    var v = this.getValue();
    var r = this.findRecord(this.valueField || this.displayField, v);
    return(this.store.indexOf(r));
  }
});

Solution 2

In Ext 4.0.2 the same code would look like:

Ext.override(Ext.form.ComboBox, {
  getSelectedIndex: function() {
    var v = this.getValue();
    var r = this.findRecord(this.valueField || this.displayField, v);
    return(this.store.indexOf(r));
  }
});

Jad, you're missing a closing parenthesis on your return statement... just thought you should know.

Solution 3

If you have a combo where valueField is the id used by the combo's store, you can simply avoid the search:

var v = combobox.getValue();
var record = combobox.findRecord(combobox.valueField || combobox.displayField, v);
var index = combobox.store.indexOf(record);

using this:

var id = combobox.getValue();
var record = store_combobox.getById(id);
Share:
47,922
Seb Nilsson
Author by

Seb Nilsson

Software Developer with focus on ASP.NET & C# Passionate about the web, HTML5 & JavaScript Active within Microsoft-technologies and Open Source Sharing knowledge from own projects

Updated on July 09, 2022

Comments

  • Seb Nilsson
    Seb Nilsson almost 2 years

    What is the certified way to determine the index of the currently selected item in a ComboBox in ExtJS?

    Is there a difference on how to do this between ExtJS 3.x and 4?

    var combo = new Ext.form.ComboBox(config);
    var selectedIndex = combo.selectedIndex; // TODO: Implement
    if(selectedIndex > 2) {
        // Do something
    }
    

    Bonus-points for how to add it as a property to the ComboBox-object.