jQuery Select2-使用选项卡选择一个选项 [英] jQuery Select2 - Use tab to select an option

查看:42
本文介绍了jQuery Select2-使用选项卡选择一个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用箭头键转到所需的select2选项,然后按Tab键选择该选项,然后照常使用Tab键选择下一个元素.

I'd like to be able to use the arrow keys to get to the select2 option I want and then press tab to select that option and then tab to the next element as usual.

我已经有了向下箭头,可以使用以下命令打开select2:

I already got the down arrow to open the select2 with the following:

$(document).on('keydown', '.select2', function(e) {
  if (e.originalEvent && e.which == 40) {
    e.preventDefault();
    $(this).siblings('select').select2('open');
  } 
});

我还可以使用箭头到达需要去的地方.现在,我正在努力使选项卡部分正常工作.

And I can also use the arrows to get where I need to go. Now I'm struggling to make the tab part work.

我假设因为select2-search__field在我按下键时就具有焦点,那是我将事件绑定到的元素吗?然后大概我需要获取当前突出显示的选项的值并触发select2更改?

I'm assuming since the select2-search__field has focus at the time I'm pressing the key, that that is the element I bind the event to? And then presumably I need to get the value of the currently highlighted option and trigger the select2 change?

我不是100%肯定这是正确的方法,但我不太清楚.

I'm not 100% sure this is the right approach but I can't quite figure it out.

推荐答案

要实现此目的,您可以使用selectOnClose: true:

To achieve this you can use selectOnClose: true:

$(document).on('keydown', '.select2', function(e) {
  if (e.originalEvent && e.which == 40) {
    e.preventDefault();
    $(this).siblings('select').select2('open');
  }
});

$('select').select2({
  selectOnClose: true
});

select {
  min-width: 150px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<select>
  <option>AAAAA</option>
  <option>BBBB</option>
  <option>CCCC</option>
  <option>DDDD</option>
  <option>EEEE</option>
  <option>FFFF</option>
  <option>GGGG</option>
</select>

这篇关于jQuery Select2-使用选项卡选择一个选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆