Question

I have a textbox that I would like to prevent the user from entering any letters in. They need to be able to enter numbers.

The textbox has an onkeypressed event already set, and I'm adding logic so that if the user enters a letter, nothing is shown.

Regardless of what I do (cancelbubble, stop propogation, return false), the letter is still getting entered in the text box. I've watched the debugger go over these and still the letter is being entered, its like it is taking place after the fact of the event.

Was it helpful?

Solution

The event handler hook you are looking for is onkeydown:

yourInput.onkeydown = function(e){
    var char = String.fromCharCode(e.which); // get the char
    return /[0-9]/.test(char);  //assert it's a number
}

working demo

Returning false from an event handler attached directly (rather than attachEvent) cancels the event.

OTHER TIPS

Actually once I got home to test onkeydown was doing the same thing, when I edited what was in the text box, it would still add the non-numeric character at the end.

Ended up using onkeyup, that appears to be far enough down the line that it will wipe out what is in the textbox.

I was really looking for the ajax filtered textbox functionality, but couldn't use that because we aren't using actual ajax controls in the application.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top