-1

Hellow all ..

Is there anyone who can help me on below Js. Right now it is working fine with me but I can't use backspace.

Below Js allow texts and I can use delete key, how to allow backspace as well.

  $(document).ready(function(){
        $("#inputTextBox").keypress(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.
            if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 )) { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
    });

1 Answers1

1

use backspace in if to check for keycode 8 and execute

if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0 ) && !(inputValue ==8)) { 
                event.preventDefault(); 
            }

for reference https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

$(document).ready(function(){
    $("input").keydown(function(event){
            var inputValue = event.which;
            // allow letters and whitespaces only.
            if(!(inputValue >= 65 && inputValue <= 123) && (inputValue != 32 && inputValue != 0) && (inputValue !=8) )
            { 
                event.preventDefault(); 
            }
            console.log(inputValue);
        });
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

</head>
<body>

  First name: <input type="text" name="FirstName" ><br>

</body>
</html>

Special keys

Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.

If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.

SOURCE

jasinth premkumar
  • 1,430
  • 1
  • 12
  • 22