Input only numbers or alphanumeric html input

Pendem Shiva Shankar
2 min readMay 31, 2021

--

For a best usabulity we are allowed to enter only numbers or numbers with albhabets excluding the symbols and special characters is a best usabulity and this is simple task but this makes the user more comfort and makes more professional.

<input type="text" id="text1" onkeypress="return IsAlphaNumeric(event);" ondrop="return false;"
onpaste="return false;" />

The complete javascript code is here

<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsAlphaNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
document.getElementById("error").style.display = ret ? "none" : "inline";
return ret;
}
</script>

considering the same and allowing only numbers

<input type="text" id="text1" onkeypress="return IsNumeric(event);" ondrop="return false;"
onpaste="return false;" />
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsNumeric(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode >= 48 && keyCode <= 57) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
console.log(ret);
return ret;
}
</script>

Allowing only characters

<input type="text" id="text1" onkeypress="return IsText(event);" ondrop="return false;"
onpaste="return false;" />
<script type="text/javascript">
var specialKeys = new Array();
specialKeys.push(8); //Backspace
specialKeys.push(9); //Tab
specialKeys.push(46); //Delete
specialKeys.push(36); //Home
specialKeys.push(35); //End
specialKeys.push(37); //Left
specialKeys.push(39); //Right
function IsText(e) {
var keyCode = e.keyCode == 0 ? e.charCode : e.keyCode;
var ret = ((keyCode == 32 ) || (keyCode >= 65 && keyCode <= 90) || (keyCode >= 97 && keyCode <= 122) || (specialKeys.indexOf(e.keyCode) != -1 && e.charCode != e.keyCode));
return ret;
}
</script>

Hope this is helpfull and can solve this issue, it would be greatly appreciated if you support me with a like or clap

For more info reach me on my telegram id @chigovera .

--

--

No responses yet