I;m trying yo implement a javacript function which will not allow to the user to input anything else than float numbers (digits)
This is my approach but I don’t know how to improve it in order to allow submition of negatives numbers also (allow ‘-‘ key) and work on IE also.
function digits_only(evt, form) { var evt = evt || window.event, targ = evt.target || evt.srcElement, charCode = evt.which || evt.keyCode, keyChar = String.fromCharCode(charCode), isValid = true; if (charCode > 13) { isValid = /[0-9.]/.test(keyChar); //if a dolt is already in input if (keyChar === '.' && /\./.test(targ.value)) { isValid = false; } } return isValid; }
I think you are looking for so called ‘input masks’. They are a lot more powerful then just allowing numbers. But you can surly use them for that. Google ‘javascript input mask’ or check out this jQuery Plugin.
EDIT: Seems like the linked plugin only supports fixed length masks, but the term may be a good starting point…