Jack Clarke
Jack Clarke

Reputation: 159

Cannot achieve cross browser compatibility for js function

The code below works for disabling the backspace key in a textarea in Firefox perfectly but not Chrome or Safari, any suggestions would be very much appreciated

$('#texttype').keypress(function(event){ 
var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '8'){ 
        return false;
    }
        event.stopPropagation();

});

Upvotes: 1

Views: 55

Answers (1)

adeneo
adeneo

Reputation: 318302

Why not use e.which, it's normalized in jQuery, and the keycode is an integer.

The keydown event triggers on any key press and gives a keycode in all browsers.

The keypress event triggers after keydown and does give a keycode, but it's only guaranteed for character keys, and does not fire on the backspace key in webkit.

$('#texttype').on('keydown', function(e) { 
    if ( e.which === 8 ) { 
        return false;
    }
    e.stopPropagation();
});

FIDDLE

Upvotes: 1

Related Questions