Javascript 只允许数字和一位小数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14609521/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:22:58  来源:igfitidea点击:

Allowing only numbers and one decimal

javascript

提问by SavvyGoat

Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.

伙计们,我有这段 JavaScript 代码,它只允许数字和一个小数点。我遇到的问题是,当我切换到我的文本框控件时,它会突出显示该值,但我按退格键擦除然后输入一个数字。这是我想防止的额外击键。

Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.

创建它的人的道具找到了(http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction),这里是代码。我把它放在 keyUp 事件上。

 <script>
  // Retrieve last key pressed.  Works in IE and Netscape.
  // Returns the numeric key code for the key pressed.
  function getKey(e)
  {
    if (window.event)
       return window.event.keyCode;
    else if (e)
       return e.which;
    else
       return null;
  }
  function restrictChars(e, obj)
  {
    var CHAR_AFTER_DP = 2;  // number of decimal places
    var validList = "0123456789.";  // allowed characters in field
    var key, keyChar;
    key = getKey(e);
    if (key == null) return true;
    // control keys
    // null, backspace, tab, carriage return, escape
    if ( key==0 || key==8 || key==9 || key==13 || key==27 )
       return true;
    // get character
    keyChar = String.fromCharCode(key);
    // check valid characters
    if (validList.indexOf(keyChar) != -1)
    {
      // check for existing decimal point
      var dp = 0;
      if( (dp = obj.value.indexOf( ".")) > -1)
      {
        if( keyChar == ".")
          return false;  // only one allowed
        else
        {
          // room for more after decimal point?
          if( obj.value.length - dp <= CHAR_AFTER_DP)
            return true;
        }
      }
      else return true;
    }
    // not a valid character
    return false;
  }
</script>

回答by sohaib

<input type="text" class="decimal" value="" />

And in Js use this

在 Js 中使用这个

$('.decimal').keyup(function(){
    var val = $(this).val();
    if(isNaN(val)){
         val = val.replace(/[^0-9\.]/g,'');
         if(val.split('.').length>2) 
             val =val.replace(/\.+$/,"");
    }
    $(this).val(val); 
});

Check this fiddle: http://jsfiddle.net/2YW8g/

检查这个小提琴:http: //jsfiddle.net/2YW8g/

THis worked for me, i have taken this answer from "Nickalchemist" and take none of its credit.

这对我有用,我从“Nickalchemist”那里得到了这个答案并且不相信它。

回答by Alex Oliveira

If you can't use an already stable and well-know library, you can try something like this:

如果你不能使用已经稳定和众所周知的库,你可以尝试这样的事情:

document.write('<input id="inputField" onkeyup="run(this)" />');

function run(field) {
    setTimeout(function() {
        var regex = /\d*\.?\d?/g;
        field.value = regex.exec(field.value);
    }, 0);
}

I know it doesn't prevent the wrong char to appear, but it works.

我知道它不会阻止错误字符的出现,但它确实有效。

PS: that setTimeout(..., 0)is a trick to execute the function after the value of the field has already been modified.

PS:这setTimeout(..., 0)是在字段的值已经被修改后执行函数的技巧。

回答by Arman Ortega

Here is a sample solution that will accept a number with one(1) decimal point only. e.g 1.12, 11.5

这是一个示例解决方案,它只接受带有一 (1) 个小数点的数字。例如 1.12、11.5

Enter a number with one(1) decimal point only<br />
<input type="text" id="decimalPt"> <br />

$('.decimalPt').keypress(function(evt) {
  evt = (evt) ? evt : window.event;
  var charCode = (evt.which) ? evt.which : evt.keyCode;
  if (charCode == 8 || charCode == 37) {
    return true;
  } else if (charCode == 46 && $(this).val().indexOf('.') != -1) {
    return false;
  } else if (charCode > 31 && charCode != 46 && (charCode < 48 || charCode > 57)) {
    return false;
  }
  return true;
});

Take a look at this: https://jsfiddle.net/sudogem/h43r6g7v/12/

看看这个:https: //jsfiddle.net/sudogem/h43r6g7v/12/

回答by mihaimm

I think it would be best to use something that already exists... like Masked Input Pluginwith jQuery

我认为最好使用已经存在的东西......比如带有jQuery的Masked Input Plugin

回答by Reshma S Raveendran

Try this,

尝试这个,

$('input').on('keydown', function (event) {
    return isNumber(event, this);
});
function isNumber(evt, element) {
    var charCode = (evt.which) ? evt.which : evt.keyCode;
    if ((charCode != 190 || $(element).val().indexOf('.') != -1)  // “.” CHECK DOT, AND ONLY ONE.
            && (charCode != 110 || $(element).val().indexOf('.') != -1)  // “.” CHECK DOT, AND ONLY ONE.
            && ((charCode < 48 && charCode != 8)
                    || (charCode > 57 && charCode < 96)
                    || charCode > 105))
        return false;
    return true;
}

回答by Edgard

Be sure to test on any browser. The accepted answer doesn't work on Firefox.

请务必在任何浏览器上进行测试。接受的答案不适用于 Firefox。

Try HTML5 type number:

尝试 HTML5 类型编号:

<input type="number" placeholder="1.0" step="0.1">

You could define min="0" max="10"

你可以定义 min="0" max="10"

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size

参考:https: //developer.mozilla.org/en-US/docs/Web/HTML/Element/input/number#Controlling_input_size

Note:type="number" is not supported in Internet Explorer 9 and earlier versions.

注意:Internet Explorer 9 及更早版本不支持 type="number"。