Restricting input to certain characters only works in Chrome, but not in Firefox

Below is a script that allows the user to enter small letters from az, numbers from 0 to 9 and a dash -. This works well in Chrome, but in Firefox, the text field does not allow input at all. What is going wrong?

$('#slug_input').keypress(function(key) {
        return((key.keyCode >= 97 && key.keyCode <= 122) || (key.keyCode >= 48 && key.keyCode <= 57) || key.keyCode == 45 );
    });
+4
source share
2 answers

event.keycodeFirefox was not supported. Use event.whichfor firefox. Check the code below, which allows only alphanumeric and hyphen.

$(function() {
  $('#slug_input').keypress(function(evt) {

    var keyID = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
    return ((keyID >= 97 && keyID <= 122) || (keyID >= 48 && keyID <= 57) || keyID == 45);

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="slug_input">
Run codeHide result

But, as the tushar suggested, I suggest you use Regex matching.

+2
source
$('#slug_input').keypress(function(key) {
    return((key.which >= 97 && key.which <= 122) || (key.which >= 48 && key.which <= 57) || key.which == 45 );
});
+3
source

Source: https://habr.com/ru/post/1621434/


All Articles