Archive for August, 2012

ExtJS 4 – clear/reset combobox

Friday, August 3rd, 2012

Surprisingly there is no native way to reset the value of a combo box. Once the user selects something in it, it can’t go back to ‘clear’ state. From this moment on the user can change the value with some other value, but can’t remove it at all. It is possible to use .setValue(”) on the ComboBox component to clear it programatically. But how exactly would you do it? Some people put additional form button with on click handler that finds the combo and .setValue-s it to empty. Other mix the combo with triggerfield and create another trigger that does the same.

These are all nice options, but are completely useless when it comes to the user’s uncanny ability to mess things up. I’ve seen a tons of users that do the following:
1. select some option in the combo
2. say ‘oh, I do not need this here’
3. mark the text in the combo’s textfield and delete it
4. hit submit
What is wrong here? The actual combo value is not dependant of the displayed text. If you remove the text, the value is still there, hidden behind the scene. And when you submit that form, the old combo value will be there and will be send to the server. And users do it all the time, it doesn’t matter if there is a big red button right next to the field that says “clear that combo”.

The easier solution for all these problems is to play along with the user. Make the combo clear its value when the text from the textfield is removed. It is not that complicated:

    xtype: 'combo',
    name: 'department_id',
    fieldLabel: 'Department',
    store: me.getDepartmentStore(),
    displayField: 'name',
    valueField: 'id',
    enableKeyEvents: true,
    listeners: {
        keyup: function(cmp){
            if (cmp.lastValue == ''){

ComboBox is descendant of Ext.form.Field.Text so you can use its key events. When the user presses BACKSPACE or DEL to remove the text, the keyup event will fire and it will check the lastValue property. Both `rawValue` and `lastValue` hold the actual text in the textfield, so if this property is empty the combo should be cleared.