简体   繁体   中英

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/

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); }

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) {
            }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM