-2

How do I restrict input fields to numeric values rather than integer values?

<input type="text" class="numericOnly">

jQ

$(".numericOnly").keypress(function (e) {
    if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
Fergoso
  • 1,584
  • 3
  • 21
  • 44

3 Answers3

1

Try this

$(".numericOnly").keypress(function(e) {

    var code = e.which;

    if(($(this).val().indexOf(".") == -1 && code == 46) || (code >= 48 && code <= 57) || (code == 51) || (code == 8) || (code >= 37 && code <= 40))
    {
        return true;
    }       

    return false;
})

.bind("paste",function(e) {

      e.preventDefault();
}); 
tliokos
  • 3,606
  • 3
  • 28
  • 28
0

If you want to allow decimal points, add them to the character class you're using. E.g. /[^0-9.]/g if a decimal point in your locale is ., or /[^0-9,]/g if it's , (as it is in some).

Of course, that would let someone type .0.0.0.1, you'll want whole-value checks on the field as well as keystroke-level checks.

Separately, remember there are lots of ways for values to get into fields other than typing (pasting, for instance), so (again) whole-value checks at some stage will be a good idea.


Side note: Use e.which, not e.keyCode. jQuery normalizes the event object, setting e.which on browsers that don't set it natively.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
-2

With Dot

Get this js file

http://thefitties.co.uk/js/plugins/jquery-numeric.js

And

In HTML

<input class="numeric" type="text">

in Script

$("input.numeric").numeric()

WITHOUT DOt

$(document).ready(function() {
    $("#txtboxToFilter").keydown(function (e) {
        // Allow: backspace, delete, tab, escape, enter and .
        if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||
             // Allow: Ctrl+A
            (e.keyCode == 65 && e.ctrlKey === true) || 
             // Allow: home, end, left, right
            (e.keyCode >= 35 && e.keyCode <= 39)) {
                 // let it happen, don't do anything
                 return;
        }
        // Ensure that it is a number and stop the keypress
        if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
            e.preventDefault();
        }
    });
});

OR

http://jsfiddle.net/lesson8/HkEuf/1/

Prashant Sarvaiya
  • 364
  • 1
  • 3
  • 14