jQuery: what is the best way to restrict “number”-only input for textboxes? (allow decimal points)

If you want to restrict input (as opposed to validation), you could work with the key events. something like this:

<input type="text" class="numbersOnly" value="" />

And:

jQuery('.numbersOnly').keyup(function () { 
    this.value = this.value.replace(/[^0-9\.]/g,'');
});

This immediately lets the user know that they can’t enter alpha characters, etc. rather than later during the validation phase.

You’ll still want to validate because the input might be filled in by cutting and pasting with the mouse or possibly by a form autocompleter that may not trigger the key events.

Leave a Comment