Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 665
Muzafar Khan Avatar asked Jul 23 '15 07:07

Muzafar Khan


2 Answers

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();
}
like image 156
AndrewR Avatar answered Sep 24 '22 08:09

AndrewR


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.

like image 36
Marcello Mönkemeyer Avatar answered Sep 26 '22 08:09

Marcello Mönkemeyer