Search code examples
javascriptjquerykeypressrestriction

jquery keypress in input text restriction, i want it to allow A-Z and white space only but my code won't allow "Y" and "Z"


Actually I didn't code this, i just copy and paste it to try.

Here's the code.

$("#firstname, #lastname").keypress(function(event) {
  var inputValue = event.charCode;
  if (!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)) {
    event.preventDefault();
  }
  $('#input').html(inputValue);
});

Solution

  • The keycode for y is 121 and likewise the keycode for z is 122. Therefore if you want to include those in the range then you should change inputValue <= 120 to inputValue <= 122.

    However, you don't need to check the keycodes for this. I'd suggest using the regular expression /[^a-z\s]/gi (which is a negated character class that will match characters that are not a-z or whitespace - case insensitive).

    You can simply replace these characters with an empty string and effectively remove them:

    $("#firstname, #lastname").on('input', function(event) {
      this.value = this.value.replace(/[^a-z\s]/gi, '');
    });
    

    Basic example:

    $("#firstname, #lastname").on('input', function(event) {
      this.value = this.value.replace(/[^a-z\s]/gi, '');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="firstname" type="text" />