jQuery: what is the best way to restrict “number”-

2019-01-01 04:53发布

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.

Update from Praveen Jeganathan

No more plugins, jQuery has implemented its own jQuery.isNumeric() added in v1.7. See: https://stackoverflow.com/a/20186188/66767

30条回答
刘海飞了
2楼-- · 2019-01-01 05:04

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);
   }
});
查看更多
余生无你
3楼-- · 2019-01-01 05:04

No need for the long code for number input restriction just try this code.

It also accepts valid int & float both values.

Javascript Approach

onload =function(){ 
  var ele = document.querySelectorAll('.number-only')[0];
  ele.onkeypress = function(e) {
     if(isNaN(this.value+""+String.fromCharCode(e.charCode)))
        return false;
  }
  ele.onpaste = function(e){
     e.preventDefault();
  }
}
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

jQuery Approach

$(function(){

  $('.number-only').keypress(function(e) {
	if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;
  })
  .on("cut copy paste",function(e){
	e.preventDefault();
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

UPDATE

The above answers are for most common use case - validating input as a number.

But below is the code snippet for special use cases

  • Allowing negative numbers
  • Showing the invalid keystroke before removing it.

$(function(){
      
  $('.number-only').keyup(function(e) {
        if(this.value!='-')
          while(isNaN(this.value))
            this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')
                                   .split('').reverse().join('');
    })
    .on("cut copy paste",function(e){
    	e.preventDefault();
    });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p> Input box that accepts only valid int and float values.</p>
<input class="number-only" type=text />

查看更多
人间绝色
4楼-- · 2019-01-01 05:05
    $(".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 ;)

查看更多
妖精总统
5楼-- · 2019-01-01 05:07

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.

查看更多
人气声优
6楼-- · 2019-01-01 05:07

You can use autoNumeric from decorplanit.com . They have a nice support for numeric, as well as currency, rounding, etc.

I have used in an IE6 environment, with few css tweaks, and it was a reasonable success.

For example, a css class numericInput could be defined, and it could be used to decorate your fields with the numeric input masks.

adapted from autoNumeric website:

$('input.numericInput').autoNumeric({aSep: '.', aDec: ','}); // very flexible!
查看更多
流年柔荑漫光年
7楼-- · 2019-01-01 05:07

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

查看更多
登录 后发表回答