简体   繁体   English

select2文本框上的按键事件不起作用

[英]Keypress event on select2 textbox is not working

I have a select2 dropdown. 我有一个select2下拉列表。

<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 用简单的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. 它不会被触发,因为每次单击select2中的下拉箭头时,都会破坏并重新创建文本框。 I have attached a fiddle for clarity. 为了清楚起见,我附上了一个小提琴。 http://jsfiddle.net/sizekumar/ckfjzkhj/ http://jsfiddle.net/sizekumar/ckfjzkhj/

Really jQuery keypress event doesn't fire on input.select2-search__field element. 确实jQuery keypress事件不会在input.select2-search__field元素上触发。 But pure js event does. 但是纯js事件确实可以。 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 我不会将其称为重复项,但我认为此答案直接适用: https : //stackoverflow.com/a/30697173/5948237

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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