Allowing ENTER key on Dojo's FilteringSelect

The nature behavior ofENTER key on Dojo's FilteringSelect is clearing out the field and cancel the drop down, to prevent the form being submitted.

I needed it to behave opposite, to enter the value to start searching.

After much googling and digging the code, turned out the solution is pretty simple. I just needed to extend theFilteringSelect widget and override some restrictions from superclasses.

Here's is the example of the code. On this example. FilteringSelect is getting its data from server side, using dstore.

require([
    'dojo/_base/declare',
    'dojo/keys',
    'dijit/form/FilteringSelect',
    'dstore/legacy/DstoreAdapter',
    'dstore/Rest',
    'dojo/domReady!'
], function (
        declare, keys, FilteringSelect, DstoreAdapter, Rest
        ) {
    // previous codes...
    // extending FilteringSelect widget
    var Xtend = declare(FilteringSelect, {
        minKeyCount: 3,

        _startSearch: function (/*String*/key) {
            // summary:
            //		Putting minimum characters
            // overrides: _SearchMixin

            if (!key || key.length < this.minKeyCount) {
                this.closeDropDown();
                return;
            }
            this.inherited(arguments);
        },

        _onKey: function (/*Event*/ evt) {
            // summary:
            //		Handles keyboard events
            // overrides: _AutoCompleterMixin

            var key = evt.charCode || evt.keyCode;
            if (key === keys.ENTER) {
                this._startSearch(this.focusNode.value);
                return;
            }
            this.inherited(arguments);
        }
    });
    // initiating extended FilteringSelect
    var fs = new Xtend({
        title: 'Campus',
        name: 'campus_id',
        required: true,
        store: new DstoreAdapter(new Rest({
            target: 'rest/dojo/Campus/',
            idProperty: 'id'
        })),
        pageSize: 10,      // giving limit(10,x) to "dstore"
        searchDelay: 250, 
        autoWidth: true,
        style: 'width: 300px;',
        trim: true,
        placeHolder: 'Type in to search selection from dropdown',
        displayedValue: '',
        labelAttr: 'name',
        searchAttr: 'name',
        maxHeight: -1 // tells _HasDropDown to fit menu within viewport
    });

    // container.addChild(fs);
    // more codes...
});

On here, the enter key starts the searching when it's pressed instead of cancelling the event.

If you have other ideas, please comment below.

Thanks.



Comments

blog comments powered by Disqus