views:

319

answers:

4

Hi there

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;
}
+4  A: 

HI, Is this a good approach? What happens if the user copies or drags some text into the input box. I think you should better do validation on submit event.

rahul
yes, validation should be added too, but what he ask for now was restricting input
Dels
But you cannot be sure by which way the user enters input. He can type, paste or even drag some text.
rahul
+1. Don't interfere with the user's typing, it's just annoying and doesn't cover all possible ways to altering the field.
bobince
client side is more cheaper...I'll do the validation on submit too
dole doug
+1  A: 

Is this on an asp.net web application? You could use the AjaxControlToolkits MaskEditExtender...

J.13.L
A: 

I have asking similar question here:
http://stackoverflow.com/questions/657492/restrict-user-input-using-javascript

but no one give the exact answer for the problem, so let's wait until WebForms 2.0 released

Dels
+2  A: 

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...

Tim Büthe