How can I validate the text-box for restricting the input for characters only in onkeypress event in Javascript
I have placed one textbox.... I want to put restriction on it ..
that digits and spe开发者_运维百科cial characters should not be allowed to input in textbox...
how can i do using onkeypress event in Javascript ???
Assuming you have an input with id of "test"
<input type="text" id="test" />
You could use javascript like this.
function handleKeyPress(e) {
var restricted = "0123456789_#!";
var key = e.keyCode || e.which;
var i=0;
for(;i<restricted.length;i++) {
if (restricted.charCodeAt(i) == key) {
e.returnValue = false;
}
}
}
document.getElementById("test").addEventListener("keypress", handleKeyPress, true);
See working demo at jsFiddle: http://jsfiddle.net/qkkgV/
精彩评论