hiren gamit
hiren gamit

Reputation: 2163

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 special characters should not be allowed to input in textbox...

how can i do using onkeypress event in Javascript ???

Upvotes: 0

Views: 2478

Answers (1)

jessegavin
jessegavin

Reputation: 75650

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/

Upvotes: 1

Related Questions