Following on from another question I asked, i really didnt seem to be getting anywhere. Due to my ineptitude. I chose the guys answer because , well he answered my question.
I am gathering I didnt ask the right question cos I have no idea what to do ..
So issue is I have input element . Keeping it simple;
<input type="text" maxlength="12" name="price" id="price" class="foo">
I want users to be able to type in numbers only and only one period ( . ) anywhere in that price. so could be 3.00 or 300.00 or 3000
Could someone please help me out, I am going goggle eyed.
The Older question asked was here Quick regex with alert
Cambraca aproach kind of works, but the best one is the last mentioned approach , you cancel the keypress event filtering the keys before it shows up instead of undoing what was already done. A consequence of changing the value after the fact is that it may affect the position of the caret in the field.
Here's an example of abstracting the idea in a cross-browser way. Somebody should port this to a jQuery plugin http://www.qodo.co.uk/assets/files/javascript-restrict-keyboard-character-input.html
Ok, I guess I'll port it. But I'm not a jQuery guy so this is an
untestedbare bones jQuery plugin that uses their code http://jsfiddle.net/mendesjuan/VNSU7/3Here is my solution(It also validates data/values copy&pasted):
To apply it to an input, do the following :
If you specify Custom as the validation type you have to specify the valid characters. eg :
You could, in the
change
event of the input, check if the number format is OK. This code will try to get the number and remove anything else: (I'm assuming you use jQuery, if not, please do)See it working here.
EDIT: if you don't have jQuery, this code does the same (at least in Chrome):
EDIT 2: not sure if I follow, but you could add this too to prevent letters and other characters before the
change
event: