The SitePoint Forums have moved.

You can now find them here.
This forum is now closed to new posts, but you can browse existing content.
You can find out more information about the move and how to open a new account (if necessary) here.
If you get stuck you can get support by emailing forums@sitepoint.com

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

Only allow numbers in input

Hi,
I'm trying to make it impossible (well, sure, you could turn off js, but anyway) to type in anything but numbers in an input.

I started with on keyup removing anything that is not 0-9, and that worked, but the problem is that the letter you type in shows for a milisecond or so, and I don't want that.

So I tried to prevent the default action, so nothing would be entered in the input unless I say so, using the event object to detect which key was pressed and then inserting it into the input if it was 0-9. Also worked, but it breaks if I were to press the arrows to add a number in the beginning, because I just append the number at the end of the input value.

I started with on keyup removing anything that is not 0-9, and that worked, but the problem is that the letter you type in shows for a milisecond or so, and I don't want that.

Seems like overkill to worry about that millisecond - the keyup method is what I've typically used and it's worked fine.

If you want to use a keypress method, you'll have to specify which specific keys are allowed to be pressed within the control (arrows, tab, delete, backspace, etc) to ensure you don't break existing functionality. This would require some sort of switch statement or array loop to check which key was pressed each time - which could delay more than a millisecond?

Well, I would only define the keydown-event on the input, and the only keys I would have allow except 0-9 would be F5, Del, backspace and left and right arrows (perhaps 2-3 more), and that check did not take enough time for my eye to notice it. It works fine, the only problem I have is if the user presses the left arrow and wants to add a number at the start.

That sounds like you're using your JS code to manipulate the text input rather than just return true or false. If the js was inline, it would be something like:

HTML Code:

<input onkeypress="return allowedKey(event);">

Then it doesn't matter where the user types in something...the function should only check what key was pressed and return true or false. Then you don't have to constantly manipulate the .value property of the form control.