I want to block special character in this code.
In other words, user can enter only alphanumeric value and use backspace for delete.
Bug: when I wrote code==8 in if condition then it allow all special characters.
<html>
<head>
<title>practice</title>
<script type="text/javascript">
function noSpecialChar(e){
if (e.keyCode)
code = e.keyCode;
else if (e.which)
code = e.which;
//code==8 => backspace
//(code>=65 && code<=90) => alphabets
//(code>=48 && code<=57) => numeric
if((code>=65 && code<=90)||(code>=48&&code<=57)||(code==8)){
return true;
}else{
return false;
}
}
</script>
</head>
<body>
<input type="text" name="txtName" id="txtName" onkeydown=" return noSpecialChar(window.event);"/>
</body>
</html>
Doing such filtering properly is tricky. The following example uses the code in “JavaScript: The Definitive Guide”, section “17.8 Text Events”. If you wish to use it, download the code from the O’Reilly server instead of directly referring to it in your code. The code uses the whenReady.js routine which you can download from https://github.com/kukawski/whenReady/blob/master/whenReady.js
It might be slightly better to modify the code so that instead of a
data-attribute, it uses apatternattribute, which would give some functionality on some browsers even when JavaScript is disabled, as well as flexibility in specifying the set of allowed characters. But then you would need to effectively implement a regular expression parser, so the gain might not correspond to the work needed.