Ext JS 4: ComboBox and the Backspace Key

I have an Ext JS 4 ComboBox with the following config:

{
	xtype: 'combo',
	fieldLabel: 'My Combo',
	emptyText: 'Select one...',
	queryMode: 'local',
	editable: false,
	lastQuery: '',
	allowBlank: false,
	forceSelection: true,
	validateOnChange: false,
	validateOnBlur: false,
	enforceMaxLength: false,
}

The important config here is “editable: false”. It turns out that if this config is set and the combobox has focus and the backspace button is pressed, the browser (IE and Chrome) will handle this event, which happens to go back one in the browser history. Not really the user experience I was looking for.

Funny how even though I’d been through my form thousands of times, I never hit the backspace key on this field. All it took was one user…

To fix it, I add the following settings to the combobox configuration:

	enableKeyEvents: true,
	listeners: {
		keydown: function(obj, e) {
			if (e.getCharCode() == e.BACKSPACE) {
				e.preventDefault();
			}
		}
	}

This prevents the backspace key event from bubbling up to the browser.

This post discusses a different aspect of comboboxes, but it help me get to the “aha – enableKeyEvents” moment. Sencha ExtJS: Allow users to find without searching in a ComboBox

Advertisements

3 comments

  1. Thanks! It looks like it’s doing this for the textfields too for both if readOnly == true or if editable == false. I created an override for this case:

    Ext.override(Ext.form.field.Text, {
    enableKeyEvents : true,
    onKeyDown: function(e) {
    if ((this.readOnly == true || this.editable == false) && e.getCharCode() == e.BACKSPACE) {
    e.preventDefault();
    }
    this.fireEvent(‘keydown’, this, e);
    }
    });

  2. Thanks for sharing this. If you have a bunch of uneditable combos that you don’t want to update with enableKeyEvents and keydown listeners, you can also add a few global listeners to one of your controllers to do this for you:

    ‘combobox’: {
    render: function( combobox, eOpts ) {
    // if combobox isn’t editable, enableKeyEvents on it (counterintuitive, I know :)…)
    if( !combobox.editable ) {
    combobox.enableKeyEvents = true;
    }
    },
    keydown: function( combobox, e, eOpts ) {
    if( !combobox.editable ) {
    // if we’re backspacing on an uneditable combobox, prevent browser history from taking over (which is SUPER annoying)
    if( e.getCharCode() == e.BACKSPACE ) {
    e.preventDefault();
    }
    }
    }
    }

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s