关于javascript:使用jQuery和Select2,“ Keypress”事件无法正常工作

“Keypress” event is not working correctly, using jQuery & Select2

我有一个论坛,可以在其中更改选项卡的功能以进入。 当用户按下输入键时,下一个输入字段将获得焦点,并以某种方式iImanage打开focusin事件上的select2选择框,从而打开select 2框。

但是,当我选择该值并在selec2 select框中按Enter时,它不会关闭,并且在Enter键按下事件时保持打开状态,但是会关闭。 当我将enter键事件更改为select2以外的任何按键事件时,关闭它并可以正常工作,但是我必须通过enter来做到这一点。

我想要的是:
当用户在select2搜索框中选择值并按Enter时,该值将关闭,并将焦点移至下一个输入字段或任何字段。

到目前为止我做了什么。

1
2
3
4
$('.search-select').on("focusin",function(event) {
    $('#s2id_form-field-select-3').select2('open');
    event.preventDefault();  
});

Select2与Enter键事件不起作用

1
2
3
4
5
6
7
$('.select2-input').on("keypress", function(e) {
            if (e.keyCode == 13) {
                $("#select2-drop-mask").click();
                $('#name').focus();
                e.preventDefault();  
                }
       });

Select2与任何有效的按键事件

1
2
3
4
5
$('.select2-input').on("keypress", function(event) {
                $("#select2-drop-mask").click();
                $('#name').focus();
                event.preventDefault();        
});

标记

1
2
3
4
5
6
7
8
 <select id="form-field-select-3" name="register_id" class="form-control search-select" required="required">
   <option value=""></option>
   <? $query=$this->dba->get_dropdown('register',array('id','name'));
      foreach($query as $key=>$value):
   ?>
   <option value="<?=$key?>"><?=$value; ?></option>}
  <? endforeach;?>
</select>

事先为错误道歉,这是我第一次使用Select2。


我认为您正在寻找keydown:

1
2
3
4
5
6
7
$('.select2-input').on("keydown", function(e) {
            if (e.keyCode == 13) {
                $("#select2-drop-mask").click();
                $('#name').focus();
                e.preventDefault();  
                }
       });

它们有些不同。
在这种情况下,按键不会在您的字段中插入任何内容。


为我工作

1
$(document).on('keyup keydown', 'input.select2-search__field', function(e) {