Chosen Jquery: remove selection when typing DEL

3

In the example Chosen - Allow Deselect on Single Selects is implemented the possibility of deselect the selection. But the same only works with the Mouse, that is, with the keyboard has not (not discovered) how to remove the selection.

For this reason, I want to implement in the Chosen , a method so that by pressing the DEL key, the filled-in value is removed (clean, that is, remove the selection without using the mouse).

So I wrote a small function that applies Chosen (settings quoted in the official examples for Chosen to work), and it also tests which key was pressed, and if it is the "DEL" key, I call the limparChosen , whose code follows:

 $('#meu_select').trigger('chosen:clear');

To trigger _this.results_reset(evt); , which is within Chosen.prototype.register_observers = function () { , I added to the file chosen.jquery.js , the following excerpt within Chosen.prototype.register_observers = function () { , just below this.form_field_jq.bind("chosen:close.chosen", function(evt) { , more or less from line 699 of original file, the following excerpt:

this.form_field_jq.bind("chosen:clear.chosen", function (evt) {
    _this.results_reset(evt);
});

To use, I test if the DEL key was pressed, and if positive, I execute:

$('#meu_select').trigger('chosen:clear');

With this, everything works properly.

However, I want an alternate way of implementing the above functionality without having to change the Chosen source code, because every time I update Chosen I have to edit the file. Which would be annoying and easy to forget.

How do I implement this feature without having to change the Chosen source code?

    
asked by anonymous 13.01.2017 / 22:15

1 answer

3

You can make an external script for this, or in a script tag as per the convenience:

$("#foco")[0].addEventListener('keyup',function(e) {
    if (e.keyCode == 46) {  
        $("#escolha").val('').trigger('chosen:updated');
        e.stopPropagation();
    }
}, true )

See working at CODEPEN .

  • id="foco" is the div that encompasses the dropdown ;
  • id="escolha" the element where Chosen is working;
  • The code for the DEL key is usually 46, but I only tested it on Windows, so check it out.

Note that there is no trigger clear, for this we change the value with .val , and we trigger chosen:updated to reflect the new value.

The idea of using addEventListener was a precious @bfavaretto tip to avoid the need to chosen:close , as I had posted in the original version of the code.

Click the comment link for more details:

  

"The trick is to intercept the event in true forces this." - bfavaretto ♦

    
14.01.2017 / 01:08