Search code examples
jquerykeycodealphanumericbackspace

Backspace/Delete not working in Jquery alphanumeric validation


Backspace/Delete not working in Mozilla Firefox for Jquery alphanumeric validation .

<input type="text" id="myTextBox" />
$("#myTextBox").bind("keypress", function(event) { 
    var charCode = event.which;

    var keyChar = String.fromCharCode(charCode); 
    return /[a-zA-Z0-9]/.test(keyChar); 
});

click here for demo


Solution

  • Use this code

    <input type="text" id="myTextBox" />
    $("#myTextBox").bind("keypress", function(event) { 
            var charCode = event.which;
    
            if(charCode == 8 || charCode == 0)
            {
                 return;
            }
            else
            {
                var keyChar = String.fromCharCode(charCode); 
                return /[a-zA-Z0-9]/.test(keyChar); 
            }
        });