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:26

This is very simple that we have already a javascript inbuilt function "isNaN" is there.

$("#numeric").keydown(function(e){
  if (isNaN(String.fromCharCode(e.which))){ 
    return false; 
  }
});
查看更多
闭嘴吧你
3楼-- · 2019-01-01 05:27

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

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true
    }
  }
});
查看更多
梦该遗忘
4楼-- · 2019-01-01 05:27

As a slight improvement to this suggestion, you can use the Validation plugin with its number(), digits, and range methods. For example, the following ensures you get a positive integer between 0 and 50:

$("#myform").validate({
  rules: {
    field: {
      required: true,
      number: true,
      digits: true,
      range : [0, 50]
    }
  }
});
查看更多
大哥的爱人
5楼-- · 2019-01-01 05:27

I first tried solving this using jQuery, but I wasn't happy about unwanted characters (non-digits) actually appearing in the input field just before being removed on keyup.

Looking for other solutions I found this:

Integers (non-negative)

<script>
  function numbersOnly(oToCheckField, oKeyEvent) {
    return oKeyEvent.charCode === 0 ||
        /\d/.test(String.fromCharCode(oKeyEvent.charCode));
  }
</script>

<form name="myForm">
<p>Enter numbers only: <input type="text" name="myInput" 
    onkeypress="return numbersOnly(this, event);" 
    onpaste="return false;" /></p>
</form>

Source: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onkeypress#Example Live example: http://jsfiddle.net/u8sZq/

Decimal points (non-negative)

To allow a single decimal point you could do something like this:

<script>
  function numbersOnly(oToCheckField, oKeyEvent) {        
    var s = String.fromCharCode(oKeyEvent.charCode);
    var containsDecimalPoint = /\./.test(oToCheckField.value);
    return oKeyEvent.charCode === 0 || /\d/.test(s) || 
        /\./.test(s) && !containsDecimalPoint;
  }
</script>

Source: Just wrote this. Seems to be working. Live example: http://jsfiddle.net/tjBsF/

Other customizations

  • To allow more symbols to be typed just add those to the regular expression that is acting as the basic char code filter.
  • To implement simple contextual restrictions, look at the current content (state) of the input field (oToCheckField.value)

Some things you could be interested in doing:

  • Only one decimal point allowed
  • Allow minus sign only if positioned at the start of the string. This would allow for negative numbers.

Shortcomings

  • The caret position is not available inside the function. This greatly reduced the contextual restrictions you can implement (e.g. no two equal consecutive symbols). Not sure what the best way to access it is.

I know the title asks for jQuery solutions, but hopefully someone will find this useful anyway.

查看更多
无色无味的生活
6楼-- · 2019-01-01 05:27

Thanks for the post Dave Aaron Smith

I edited your answer to accept decimal point and number's from number section. This work perfect for me.

$(".numeric").keypress(function(event) {
  // Backspace, tab, enter, end, home, left, right,decimal(.)in number part, decimal(.) in alphabet
  // We don't support the del key in Opera because del == . == 46.
  var controlKeys = [8, 9, 13, 35, 36, 37, 39,110,190];
  // 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
      (96 <= event.which && event.which <= 106) || // Always 1 through 9 from number section 
      (48 == event.which && $(this).attr("value")) || // No 0 first digit
      (96 == event.which && $(this).attr("value")) || // No 0 first digit from number section
      isControlKey) { // Opera assigns values for control keys.
    return;
  } else {
    event.preventDefault();
  }
});
查看更多
若你有天会懂
7楼-- · 2019-01-01 05:30

This function does the same thing, uses some of the ideas above.

$field.keyup(function(){
    var val = $j(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) val =val.replace(/\.+$/,"");
    }
    $j(this).val(val); 
});
  • show visual feedback (incorrect letter appears before disappearing)
  • allows decimals
  • catches multiple "."
  • has no issues with left/right del etc.
查看更多
登录 后发表回答