views:

10477

answers:

10

What is the best way to restrict "number"-only input for textboxes?

I am looking for something that allows decimal points.

I see a lot of examples. But have yet to decide which one to use.

+1  A: 

You can use the Validation plugin with its number() method.

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});
Dror
+1  A: 

The best way is to check the contects of the text box whenever it loses focus.

You can check whether the contents are a "number" using a regular expression.

Or you can use the Validation plugin, which basically does this automatically.

Here Be Wolves
The regular expression would be /^\d*\.{0,1}\d+$/
Chetan Sastry
+13  A: 

I've successfully implemented many forms with jquery.numeric plugin.

$(document).ready(function(){
    $(".numeric").numeric();
});

Moreover this works with textareas also!

TheVillageIdiot
nice plugin, used myself
monkeylee
This plugin doesn't allow you to use backspace in Opera.
Darryl Hein
@Darryl the source is only a few dozen lines long, so I'm sure modifying it to allow that is trivial. I just found this plugin and modified it so that there is now an `allowDecimal` option for whenever I only want to allow integer values.. the source is very simple and well written.
Earlz
+15  A: 

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.

Keith Bentrup
+1 - I was going to suggest this same thing. It's a very good point to note that this form of validation can take place per keystroke, rather than once at the end. The only thing I'd add is some form of alert that what the user is typing is being rejected. Simply not showing the letters will make all-too-many people think their keyboard is broken. perhaps subtly change the background or border colour.. just as long as the user knows that your app is actually doing something.
nickf
agreed. i have an example at http://www.tarbuilders.com/. if you click "contact", the form checks the user input on the fly and if it's valid, there's a green border and check mark. invalid -> red and "x"
Keith Bentrup
A: 

Just run the contents through parseFloat(). It will return NaN on invalid input.

Maciej Łebkowski
+1  A: 

I just found an even better plug-in. Gives you much more control. Say you have a DOB field where you need it be numeric but also accepts "/" or "-" characters.

It works great!

Check it out at http://itgroup.com.ph/alphanumeric/.

Bachir El Khoury
+4  A: 

The jquery.numeric plugin has some bugs that I notified the author of. It allows multiple decimal points in Safari and Opera, and you can't type backspace, arrow keys, or several other control characters in Opera. I needed positive integer input so I ended up just writing my own in the end.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});
Dave Aaron Smith
A: 

Check this find code for Database use:

function numonly(root){
    >>var reet = root.value;
    var arr1 = reet.length;
    var ruut = reet.charAt(arr1-1);
    >>>if (reet.length > 0){
        var regex = /[0-9]|\./;
        if (!ruut.match(regex)){
            var reet = reet.slice(0, -1);
            $(root).val(reet);
        >>>>}
    }
}
//Then use the even handler onkeyup='numonly(this)'
Alex Homm
A: 
    $(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39];
  // IE doesn't support indexOf
  var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
  // Some browsers just don't raise events for control keys. Easy.
  // e.g. Safari backspace.
  if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
      (49 <= event.which && event.which <= 57) || // Always 1 through 9
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});

This code worked pretty good on me, I just had to add the 46 in the controlKeys array to use the period, though I don't thinks is the best way to do it ;)

Reedyseth
A: 

@Reedyseth : thanks for the good code

bilelz