jQuery Select2 - Use tab to select an option

不羁的心 提交于 2020-12-14 06:34:20

问题


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.

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.

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?

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


回答1:


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>



回答2:


Just add following line in your code.

$(document).on("select2:close", '.select2-hidden-accessible', function () { $(this).focus(); });

Your issue will be resolved.



来源:https://stackoverflow.com/questions/50605279/jquery-select2-use-tab-to-select-an-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!