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
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>
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.