Skip to content
Advertisement

Text Input: Limit input to numbers (0-9) and the minus sign (-). Not working as expected

I am trying to limit keyboard input in my text field to numbers [0-9] and the minus sign - only (no copy/paste, etc.) and the delete key obviously.

The code works for limiting to numbers and the delete key but it doesn’t work for the minus sign - part.

The user should only be able to enter a minus sign - in front of their number, if they try to enter 1 then - it should not input the - but right now the - part doesn’t work at all.

Fiddle: http://jsfiddle.net/7XLqQ/1/

I think this piece of code is the issue but it looks fine. It checks that the text input is blank and if so it input the minus sign -.

JavaScript

My full code:

JavaScript

Advertisement

Answer

I’d suggest:

JavaScript

JS Fiddle demo.

The reason your original code failed is simply that you’d already returned from the function before the if condition could be assessed. In this version if the - key is pressed a ternary returns true if there is no current value (so the - will be the first character), or false if there is already a value (and therefore the - will not be the first character).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement