Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you restrict input box to allow only numbers and decimals?

To restrict input to allow only numbers and decimal point in a textbox with JavaScript, we can call the string match method to validate the input value. form. onsubmit = () => { return textarea. value.

How do I limit the number of decimal places in JavaScript?

To limit decimal places in JavaScript, use the toFixed() method by specifying the number of decimal places.

How do you limit a variable to two decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do you restrict numbers in JavaScript?

The standard solution to restrict a user to enter only numeric values is to use <input> elements of type number. It has built-in validation to reject non-numerical values.


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.


Update

There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

jquery.numeric plugin

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

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

Moreover this works with textareas also!

However, note that Ctrl+A, Copy+Paste (via context menu) and Drag+Drop will not work as expected.

HTML 5

With wider support for the HTML 5 standard, we can use pattern attribute and number type for input elements to restrict number only input. In some browsers (notably Google Chrome), it works to restrict pasting non-numeric content as well. More information about number and other newer input types is available here.


I thought that the best answer was the one above to just do this.

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

but I agree that it is a bit of a pain that the arrow keys and delete button snap cursor to the end of the string ( and because of that it was kicked back to me in testing)

I added in a simple change

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

this way if there is any button hit that is not going to cause the text to be changed just ignore it. With this you can hit arrows and delete without jumping to the end but it clears out any non numeric text.


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();
  }
});

No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7.

jQuery.isNumeric( value )

Determines whether its argument is anumber.

Samples results

$.isNumeric( "-10" );     // true
$.isNumeric( 16 );        // true
$.isNumeric( 0xFF );      // true
$.isNumeric( "0xFF" );    // true
$.isNumeric( "8e5" );     // true (exponential notation string)
$.isNumeric( 3.1415 );    // true
$.isNumeric( +10 );       // true
$.isNumeric( 0144 );      // true (octal integer literal)
$.isNumeric( "" );        // false
$.isNumeric({});          // false (empty object)
$.isNumeric( NaN );       // false
$.isNumeric( null );      // false
$.isNumeric( true );      // false
$.isNumeric( Infinity );  // false
$.isNumeric( undefined ); // false

Here is an example of how to tie the isNumeric() in with the event listener

$(document).on('keyup', '.numeric-only', function(event) {
   var v = this.value;
   if($.isNumeric(v) === false) {
        //chop off the last char entered
        this.value = this.value.slice(0,-1);
   }
});