How to capture enter key press for select2

后端 未结 2 1006
半阙折子戏
半阙折子戏 2021-01-22 12:10

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

相关标签:
2条回答
  • 2021-01-22 12:58

    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>

    0 讨论(0)
  • 2021-01-22 13:01

    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.

    0 讨论(0)
提交回复
热议问题