HTML文本输入仅允许数字输入

JavaScript

老丝阿飞

2020-03-10

有没有一种快速的方法来将HTML文本输入(<input type=text />)设置为仅允许数字键击(加'。')?

第469篇《HTML文本输入仅允许数字输入》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

16个回答
Green小哥Tom 2020.03.10

The best way (allow ALL type of numbers - real negative, real positive, iinteger negative, integer positive) is:

$(input).keypress(function (evt){
    var theEvent = evt || window.event;
    var key = theEvent.keyCode || theEvent.which;
    key = String.fromCharCode( key );
    var regex = /[-\d\.]/; // dowolna liczba (+- ,.) :)
    var objRegex = /^-?\d*[\.]?\d*$/;
    var val = $(evt.target).val();
    if(!regex.test(key) || !objRegex.test(val+key) || 
            !theEvent.keyCode == 46 || !theEvent.keyCode == 8) {
        theEvent.returnValue = false;
        if(theEvent.preventDefault) theEvent.preventDefault();
    };
}); 
十三Davaid 2020.03.10

I saw some great answers however I like them as small and as simple as possible, so maybe someone will benefit from it. I would use javascript Number() and isNaN functionality like this:

if(isNaN(Number(str))) {
   // ... Exception it is NOT a number
} else {
   // ... Do something you have a number
}

Hope this helps.

神乐 2020.03.10

This is an improved function:

function validateNumber(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  if ((key < 48 || key > 57) && !(key == 8 || key == 9 || key == 13 || key == 37 || key == 39 || key == 46) ){
    theEvent.returnValue = false;
    if (theEvent.preventDefault) theEvent.preventDefault();
  }
}
前端小胖JinJin 2020.03.10

使用此DOM:

<input type = "text" onkeydown = "validate(event)"/>

这个脚本:

validate = function(evt)
{
    if ([8, 46, 37, 39, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 35, 36].indexOf(evt.keyCode || evt.which) == -1)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

...或者这个脚本,没有indexOf,使用两个for...

validate = function(evt)
{
    var CharValidate = new Array("08", "046", "039", "948", "235");
    var number_pressed = false;
    for (i = 0; i < 5; i++)
    {
        for (Ncount = 0; Ncount < parseInt(CharValidate[i].substring(0, 1)) + 1; Ncount++)
        {
            if ((evt.keyCode || evt.which) == parseInt(CharValidate[i].substring(1, CharValidate[i].lenght)) + Ncount)
            {
                number_pressed = true;
            }
        }
    }
    if (number_pressed == false)
    {
        evt.returnValue = false;
        if(evt.preventDefault){evt.preventDefault();}
    }
}

我使用onkeydown属性而不是onkeypress,因为onkeydown属性先于onkeypress属性被检查。问题可能出在Google Chrome浏览器中。

With the attribute "onkeypress", TAB would be uncontrollable with "preventDefault" on google chrome, however, with the attribute "onkeydown", TAB becomes controllable!

ASCII Code for TAB => 9

The first script have less code than the second, however, the array of ASCII characters must have all the keys.

The second script is much bigger than the first, but the array does not need all keys. The first digit in each position of the array is the number of times each position will be read. For each reading, will be incremented 1 to the next one. For example:




NCount = 0

48 + NCount = 48

NCount + +

48 + NCount = 49

NCount + +

...

48 + NCount = 57




In the case of numerical keys are only 10 (0 - 9), but if they were 1 million it would not make sense to create an array with all these keys.

ASCII codes:

  • 8 ==> (Backspace);
  • 46 => (Delete);
  • 37 => (left arrow);
  • 39 => (right arrow);
  • 48 - 57 => (numbers);
  • 36 => (home);
  • 35 => (end);
村村伽罗Mandy 2020.03.10

只需使用type =“ number”,现在此属性在大多数浏览器中均受支持

<input type="number" maxlength="3" ng-bind="first">
十三西里古一 2020.03.10

您还可以将输入值(默认情况下视为字符串)与强制为数字的自身进行比较,例如:

if(event.target.value == event.target.value * 1) {
    // returns true if input value is numeric string
}

但是,您需要将其绑定到诸如keyup等事件。

StafanHarry 2020.03.10

input type="number" 是HTML5属性。

在其他情况下,这将帮助您:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input type="number" name="somecode" onkeypress="return isNumberKey(event)"/>
Sam飞云 2020.03.10

jQuery使用的另一个变体

$(".numeric").keypress(function() {
    return (/\d/.test(String.fromCharCode(event.which) ))
});
猴子神无 2020.03.10

您可以为此使用模式:

<input id="numbers" pattern="[0-9.]+" type="number">

在这里,您可以看到完整的移动网站界面提示

老丝 2020.03.10

如果要向设备(例如手机)建议字母或数字之间的字符,则可以使用<input type="number">

乐ASam 2020.03.10

2个解决方案:

使用表单验证器(例如,使用jQuery验证插件

使用正则表达式在输入字段的onblur事件(即用户离开字段时)期间进行检查:

<script type="text/javascript">
function testField(field) {
    var regExpr = new RegExp("^\d*\.?\d*$");
    if (!regExpr.test(field.value)) {
      // Case of error
      field.value = "";
    }
}

</script>

<input type="text" ... onblur="testField(this);"/>
逆天米亚 2020.03.10

HTML5支持正则表达式,因此您可以使用以下命令:

<input id="numbersOnly" pattern="[0-9.]+" type="text">

警告:某些浏览器尚不支持此功能。

猪猪十三 2020.03.10

的JavaScript

function validateNumber(evt) {
    var e = evt || window.event;
    var key = e.keyCode || e.which;

    if (!e.shiftKey && !e.altKey && !e.ctrlKey &&
    // numbers   
    key >= 48 && key <= 57 ||
    // Numeric keypad
    key >= 96 && key <= 105 ||
    // Backspace and Tab and Enter
    key == 8 || key == 9 || key == 13 ||
    // Home and End
    key == 35 || key == 36 ||
    // left and right arrows
    key == 37 || key == 39 ||
    // Del and Ins
    key == 46 || key == 45) {
        // input is VALID
    }
    else {
        // input is INVALID
        e.returnValue = false;
        if (e.preventDefault) e.preventDefault();
    }
}

另外,您可以添加逗号,句号和减号(,.-)

  // comma, period and minus, . on keypad
  key == 190 || key == 188 || key == 109 || key == 110 ||

的HTML

<input type="text" onkeydown="validateNumber(event);"/ >
前端Tom 2020.03.10

我选择使用这里提到的两个答案的组合,即

<input type="number" />

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    return !(charCode > 31 && (charCode < 48 || charCode > 57));
}

<input type="text" onkeypress="return isNumberKey(event);">

Eva达蒙 2020.03.10

HTML5具有<input type=number>,它听起来很适合您。当前,只有Opera本身支持它,但是有一个项目具有JavaScript实现。

null 2020.03.10

我一直在努力寻找一个好的答案,我们非常需要它<input type="number",但除此之外,这两种是我想出的最简洁的方法:

<input type="text" 
       onkeyup="this.value=this.value.replace(/[^\d]/,'')">

如果您不喜欢在删除之前一秒钟显示的不可接受字符,则可以使用以下方法。请注意众多其他条件,这是为了避免禁用各种导航和热键。如果有人知道如何压缩它,请告诉我们!

<input type="text" 
onkeydown="return ( event.ctrlKey || event.altKey 
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false) 
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9) 
                    || (event.keyCode>34 && event.keyCode<40) 
                    || (event.keyCode==46) )">

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android