How to capture enter key press for select2

只愿长相守 提交于 2019-12-02 06:32:40

问题


I have a select2 dropdown for countries (multiselect). When user types keywords, it shows the related items in the menu.
For e.g., if user types ind, the menu shows India and Indonesia. If the enter key is pressed, the first item (India) is selected. This is the default behavior.

Now, I would like to select both the countries when user types ind and presses enter.

$(".select2-search__field").on("keyup",  function (e) { 
    console.log(e.keyCode);       
    if (e.keyCode == 13) {
        alert();
    }
});

With the above code, the console logs show up for i, n & d but not for the Enter key, and hence the alert never shows.
I guess the default select2 behavior is preventing my code to be triggered.

What should I do, so that I can capture the enter key press.

https://jsfiddle.net/bwp0svq6/1/


回答1:


The keypress event has been deprecated. You may want to use keydown instead.

$(document).ready(function() {
  $('#example').select2();

  $(".select2-search__field").on("keydown", function(e) {
    if (e.keyCode == 13) {
      alert();
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://rawgit.com/select2/select2/master/dist/js/select2.js"></script>
<link href="https://rawgit.com/select2/select2/master/dist/css/select2.min.css" rel="stylesheet" />

<select id="example" multiple="multiple" style="width: 300px">
  <option value="1">Argentina</option>
  <option value="2">Brazil</option>
  <option value="3">China</option>
  <option value="4">India</option>
  <option value="5">Indonesia</option>
</select>



回答2:


Why not simply use this code to check as there can be a mouse click :

   

$('#example').select2();

$("#example").on("click change keydown", function (e) { 
        var keycode = (event.keyCode ? event.keyCode : event.which);       
        if (keycode == 13) {
            console.log('inside')
        }
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="example" multiple="multiple" style="width: 300px">
    <option value="1">Argentina</option>
    <option value="2">Brazil</option>
    <option value="3">China</option>
    <option value="4">India</option>
    <option value="5">Indonesia</option>    
</select>

Hope this helps.



来源:https://stackoverflow.com/questions/55037611/how-to-capture-enter-key-press-for-select2

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