Sathish
Sathish

Reputation: 419

Keypress event on select2 textbox is not working

I have a select2 dropdown.

<select class="eselect2" type="text" id="qename" style="width: 390px;"> 

                    <option value="1">NY</option>
          <option value="2">MA</option>
          <option value="3">PA</option>
          <option value="4">CA</option>
                </select>

with simple javascript

$( document ).ready(function() {
    console.log( "ready!" );
    $(".eselect2").select2();
    $('.select2-search__field').on("keydown", function(e) {
                    console.log(e.keyCode); // nothing happens
            if (e.keyCode == 13) {
                }
       });
});

I have an event associated with keypress on the input field. It does not get fired since, the textbox is destroyed and recreated each time the dropdown arrow in the select2 is clicked. I have attached a fiddle for clarity. http://jsfiddle.net/sizekumar/ckfjzkhj/

Upvotes: 0

Views: 4175

Answers (2)

vkabachenko
vkabachenko

Reputation: 261

Really jQuery keypress event doesn't fire on input.select2-search__field element. But pure js event does. This piece of code works for me

document.getElementsByClassName('select2-search__field')[0].onkeypress = function(evt) { console.log(evt); }

Upvotes: 1

Vivek Chavda
Vivek Chavda

Reputation: 473

EDIT: This doesn't solve the problem.

I wouldn't call this a duplicate, but I think this answer directly applies: https://stackoverflow.com/a/30697173/5948237

$('.select2-input').on("keydown", function(e) {
        if (e.keyCode == 13) {
            }
});

Upvotes: 0

Related Questions