You will need to use a more specific selector than .select2-search__field
in your event handler, since all Select2s have that class. You can use the selectionCssClass
configuration option to associate a custom CSS class with each Select2’s selection container (which contains the .select2-search__field
). If you are initializing all of your Select2s with a single select2()
call (for example, $(select).select2({...}), then your best bet is to include a unique class name in each of your
s, and use the ":all:" value for the
selectionCssClass` configuration option.
For example, in your HTML:
<select id="..." class="numbers-only">
<!-- <option>s for this select ... -->
</select>
...
<select id="..." class="letters-only">
<!-- <option>s for this select ... -->
</select>
And in your JavaScript:
$(document).ready(function() {
$(select).select2({
selectionCssClass: ":all:",
// other configuration options
});
// ...
$(document).on('keydown', '.select2-search__field', function(event) {
const target = event.target;
const containerClasses = target.nearest('.select2-container').className;
const selectType = containerClasses.contains("numbers-only")
? "numbers"
: containerClasses.contains("letters-only")
? "letters"
: "other";
// Now selectType is one of "numbers", "letters" or "other".
if (selectType === "numbers") {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
} else if (selectType === "letters") {
if (event.keyCode < 65 || event.keyCode > 91) {
event.preventDefault();
}
}
}); // end of keydown handler.
// ...
}); // end of $(document).ready() callback.
Notes:
- By using the
keydown
event instead of the keypress
event (which is deprecated, by the way), you can prevent invalid keypresses from registering in the input field at all, so you don’t need to remove them from the input field’s value.
- I haven’t tested this code, so it might have some bugs, but you should be able to follow the general approach outlined here.
Good luck with your project!