如何限制 html 输入框,使其只接受数字输入?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5631413/
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-29 07:54:58  来源:igfitidea点击:

How can I limit a html input box so that it only accepts numeric input?

html

提问by vickey

I have an html input box, but only numeric data is data. How can I enforce that?

我有一个 html 输入框,但只有数字数据是数据。我该如何强制执行?

回答by Fynn

You can use HTML5 to validate the type of your input without using JavaScript. However, this method is not (yet) supported by all browsers.

您可以使用 HTML5 来验证输入的类型,而无需使用 JavaScript。但是,并非(还)所有浏览器都支持此方法。

<input type="number" name="quantity" min="1" max="5">

Use the following attributes to specify restrictions (as described here):

使用下面的属性来指定限制(如描述这里):

  • max- specifies the maximum value allowed
  • min- specifies the minimum value allowed
  • step- specifies the legal number intervals
  • value- Specifies the default value
  • max- 指定允许的最大值
  • min- 指定允许的最小值
  • step- 指定合法的数字区间
  • value- 指定默认值

回答by ace

You will need an events to validate if the entered text is a number or not. See sample code

您将需要一个事件来验证输入的文本是否为数字。查看示例代码

JS

JS

function isValidChar(char){

    var txt = char;
    var found = false;
    var validChars = "0123456789"; //List of valid characters

    for(j=0;j<txt.length;j++){ //Will look through the value of text
        var c = txt.charAt(j);
        found = false;
        for(x=0;x<validChars.length;x++){
            if(c==validChars.charAt(x)){
                found=true;
                break;
            }
        }
        if(!found){
            //If invalid character is found remove it and return the valid character(s).
            document.getElementById('txtFld').value = char.substring(0, char.length -1);
            break;
        }
    }
}

HTML

HTML

<input type="text" id="txtFld" onKeyup="isValidChar(this.value);" />

See working code here jsfiddle

在这里查看工作代码jsfiddle

Though the code is a bit long you can minimize if you know how to use regular expression or a jquery.

尽管代码有点长,但如果您知道如何使用正则表达式或 jquery,则可以将其最小化。

回答by i_thamary

Try this and it is up to you to select the minimum number and maximum:

试试这个,由您来选择最小数量和最大数量:

legend {
    background-color: #000;
    color: #fff;
    padding: 3px 6px;
}

.output {
    font: 1rem 'Fira Sans', sans-serif;
}

input,
label {
    width: 43%;
}

input {
    margin: 1rem 0;
}

label {
    display: inline-block;
    font-size: .8rem;
}

input:invalid + span:after {
    content: '?';
    color: #f00;
    padding-left: 5px;
}

input:valid + span:after {
    content: '?';
    color: #26b72b;
    padding-left: 5px;
}
 <span class="validity"></span>

<input type="number" id="userId" name="userId"
           placeholder="Min: 1, max: 10000"
           min="1" max="10000" />
    <span class="validity"></span>

回答by tavi

Try this code. work even on ctrl+v(paste)...

试试这个代码。即使在 ctrl+v(paste) 上也能工作...

<SCRIPT Language ="VBScript"> 

sub onlyNumber(idBox)

    Set objInl = CreateObject("VBScript.RegExp")

    objInl.Global = True

    objInl.Pattern = "[^0-9\-\.]"

    document.getElementById(idBox).value = objInl.Replace(document.getElementById(idBox).value, "")

    set objInl = nothing

end sub

</SCRIPT>


 <input type="text" id="txtFld" onKeyup="onlyNumber(this.id);" />

回答by hinekyle

Number() is the function you want "123a" returns NAN

Number() 是你想要的函数 "123a" 返回 NAN

parseInt() truncates trailing letters "123a" returns 123

parseInt() 截断尾随字母“123a”返回 123

<input type="text" id="txtFld" onblur="if(!Number(this.value)){alert('not a number');}" />

回答by Javed Akram

<input name="txtnumbersOnly"  type="text" onkeypress="if (event.keyCode < 45 || event.keyCode > 57) event.returnValue = false;">

回答by Ali Murtaza

Use java script function as a validator. Or you can get the jquery funcations as well.

使用 java 脚本函数作为验证器。或者您也可以获得 jquery 功能。