Muzafar Khan
Muzafar Khan

Reputation: 827

Backspace key issue in firefox

I have an text box and applied Allow Alphabets With Space only using jquery. Its working in chrome But in firefox the backspace key is not working.

<input type="text" placeholder="" id="id1">

$(function(){
$('#id1').keypress(function (event) {
      if ((event.which >= 65 && event.which < 91) || (event.which > 96 && event.which < 123) || event.which === 32 || event.which===0) {
          return true;
      }
        else {
          event.preventDefault();
      }
 })});

Here it is Plnkr

Upvotes: 7

Views: 6088

Answers (2)

AndrewR
AndrewR

Reputation: 6748

It is a difference in how the browsers handle the backspace character. In Chrome, backspace never makes it to the keypress event handler, but in Firefox it does.

If you add || event.which === 8 to your conditional, you'll allow backspace and return true, which will get it working in Firefox.

EDIT: Arrow Up, Down,Left, Right and Tab also doesn't work in firefox.

var ignoredKeys = [8, 9, 37, 38, 39, 40];

if (ignoredKeys.indexOf(event.which) >=0 || (event.which >= 65 && event.which < 91) || (event.which > 96 && event.which < 123) || event.which === 32 || event.which===0) {
    return true;
} else {
    event.preventDefault();
}

Upvotes: 11

This should work in all [major] browsers:

$('#id1').keydown(function (event) {
    if (event.which == 8) {
        // ...
    } else {
        event.preventDefault();
    }
);

Note the use of keydown instead of keypress, which is essential for it to work.

Upvotes: 1

Related Questions