如何让 HTML 输入标签只接受数值?

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

How to make HTML input tag only accept numerical values?

htmlinputnumbersvalidating

提问by Chiel ten Brinke

I need to make sure that a certain <input>field only takes numbers as value. The input is not part of a form. Hence it doesn't get submitted, so validating during submission is not an option. I want the user to be unable to type in any characters other than numbers.

我需要确保某个<input>字段只将数字作为值。输入不是表单的一部分。因此它不会被提交,所以在提交期间验证不是一种选择。我希望用户不能输入数字以外的任何字符。

Is there a neat way to achieve this?

有没有一种巧妙的方法来实现这一目标?

回答by Viral Patel

HTML 5

HTML 5

You can use HTML5 input type numberto restrict only number entries:

您可以使用HTML5 输入类型 number来限制仅数字条目:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

这仅适用于 HTML5 投诉浏览器。确保您的 html 文档的 doctype 是:

<!DOCTYPE html>

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfillfor transparent support in older browsers.

另请参阅https://github.com/jonstipe/number-polyfill以了解旧浏览器中的透明支持。

JavaScript

JavaScript

Update:There is a new and very simple solution for this:

更新:有一个新的非常简单的解决方案:

It allows you to use anykind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

它允许您对文本使用任何类型的输入过滤器<input>,包括各种数字过滤器。这将正确处理复制+粘贴、拖放、键盘快捷键、上下文菜单操作、不可键入的键和所有键盘布局。

See this answeror try it yourself on JSFiddle.

请参阅此答案在 JSFiddle 上自行尝试。

For general purpose, you can have JS validation as below:

对于一般用途,您可以进行 JS 验证,如下所示:

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

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

如果你想允许小数用这个替换“if condition”:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

来源:HTML 文本输入只允许数字输入

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/

JSFiddle 演示:http: //jsfiddle.net/viralpatel/nSjy7/

回答by martincarlin87

You can also use the pattern attribute in html5:

你也可以在 html5 中使用 pattern 属性:

<input type="text" name="name" pattern="[0-9]" title="Title" /> 

Input validation tutorial

输入验证教程

Although, if your doctype isn't htmlthen I think you'll need to use some javascript/jquery.

虽然,如果您的文档类型不是,html那么我认为您需要使用一些 javascript/jquery。

回答by abhijithvijayan

Quick and Easy Code

快速简便的代码

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || (event.charCode >= 48 && event.charCode <= 57))" />

This will permit usage of numbers and backspace only.

这将只允许使用数字和退格。

If you need decimal part too, use this code fragment

如果您也需要小数部分,请使用此代码片段

<input type="text" onkeypress="return (event.charCode !=8 && event.charCode ==0 || ( event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)))" />

回答by subindas pm

Please try this code along with the input field itself

请尝试此代码以及输入字段本身

<input type="text" name="price" id="price_per_ticket" class="calculator-input" onkeypress="return event.charCode >= 48 && event.charCode <= 57"></div>

it will work fine.

它会正常工作。

回答by starbeamrainbowlabs

You can use an <input type="number" />. This will only allow numbers to be entered into othe input box.

您可以使用一个<input type="number" />. 这将只允许将数字输入到其他输入框中。

Example: http://jsfiddle.net/SPqY3/

示例:http: //jsfiddle.net/SPqY3/

Please note that the input type="number"tag is only supported in newer browsers.

请注意,输入type="number"标签仅在较新的浏览器中受支持。

For firefox, you can validate the input by using javascript:

对于 Firefox,您可以使用 javascript 验证输入:

http://jsfiddle.net/VmtF5/

http://jsfiddle.net/VmtF5/

Update 2018-03-12:Browser support is much better now it's supported by the following:

2018 年 3 月 12 日更新:浏览器支持好多了,现在它由以下支持:

  • Chrome 6+
  • Firefox 29+
  • Opera 10.1+
  • Safari 5+
  • Edge
  • (Internet Explorer 10+)
  • 铬 6+
  • 火狐 29+
  • 歌剧 10.1+
  • Safari 5+
  • 边缘
  • (Internet Explorer 10+)

回答by Fredrick Gauss

<input type="text" name="myinput" id="myinput" onkeypress="return isNumber(event);" />

and in the js:

在 js 中:

function isNumber(e){
    e = e || window.event;
    var charCode = e.which ? e.which : e.keyCode;
    return /\d/.test(String.fromCharCode(charCode));
}

or you can write it in a complicated bu useful way:

或者你可以用一种复杂但有用的方式编写它:

<input onkeypress="return /\d/.test(String.fromCharCode(((event||window.event).which||(event||window.event).which)));" type="text" name="myinput" id="myinput" />

Note:cross-browser and regex in literal.

注意:文字中的跨浏览器和正则表达式。

回答by Shaktish

I have used regular expression to replace the input value with the pattern needed.

我使用正则表达式将输入值替换为所需的模式。

var userName = document.querySelector('#numberField');

userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {  
  var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
  this.value = newValue;
}
  
<input type="text" id="numberField">

回答by Sameh Saeed

function AllowOnlyNumbers(e) {

e = (e) ? e : window.event;
var clipboardData = e.clipboardData ? e.clipboardData : window.clipboardData;
var key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
var str = (e.type && e.type == "paste") ? clipboardData.getData('Text') : String.fromCharCode(key);

return (/^\d+$/.test(str));
}
<h1>Integer Textbox</h1>
    <input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" />

JSFiddle: https://jsfiddle.net/ug8pvysc/

JSFiddle:https://jsfiddle.net/ug8pvysc/

回答by user40521

<input 
    onkeyup="value=isNaN(parseFloat(value))?1000:value" 
       type="number" 
      value="1000"
>

onkeyuptriggers when the key is released.

onkeyup松开按键时触发。

isNaN(parseFloat(value))?checks if the input value is not a number.

isNaN(parseFloat(value))?检查输入值是否不是数字。

If it is not a number the value is set to 1000 :If it is a number the value is set to the value.

如果它不是数字,则该值设置为 1000:如果它是一个数字,则该值设置为该值。

note:For some reason it only works with type="number"

注意:由于某种原因,它只适用于type="number"

To make it even more exiting, you can also have a boundary:

为了让它更精彩,你还可以有一个边界:

<input 
    onkeyup="value=isNaN(parseFloat(value))||value<0||value>9000?1000:value"
       type="number"
      value="1000"
>

Enjoy!

享受!

回答by Isaiah

I fought with this one for a bit. Many solutions here and elsewhere seemed complicated. This solution uses jQuery/javascriptalongside HTML.

我和这个吵了一会儿。这里和其他地方的许多解决方案似乎很复杂。此解决方案将jQuery/javascript与 HTML 一起使用。

    <input type="number" min="1" class="validateNumber">

    $(document).on('change', '.validateNumber', function() { 
        var abc = parseInt($(this).val());
        if(isNaN(abc)) { abc = 1; }
        $(this).val(abc);
    });

In my case I was tracking small quantities with a minimum value of 1, hence the min="1" in the input tag and abc = 1 in the isNaN() check. For positive only numbers you could change those values to 0 and even simply remove the min="1" from the input tag to allow for negative numbers.

在我的情况下,我正在跟踪最小值为 1 的小数量,因此输入标签中的 min="1" 和 isNaN() 检查中的 abc = 1。对于仅正数,您可以将这些值更改为 0,甚至只需从输入标记中删除 min="1" 以允许负数。

Also this works for multiple boxes (and could save you some load time over doing them individually by id), just add the "validateNumber" class where needed.

这也适用于多个盒子(并且可以为您节省一些加载时间而不是通过 id 单独执行它们),只需在需要的地方添加“validateNumber”类。

Explanation

解释

parseInt() basically does what you need, except that it returns NaN rather than some integer value. With a simple if() you can set the "fallback" value that you prefer in all the cases NaN is returned :-). Also W3 states herethat the global version of NaN will type cast before checking which gives some extra proofing (Number.isNaN() does not do that). Any values sent to a server/backend should still be validated there!

parseInt() 基本上可以满足您的需求,只是它返回 NaN 而不是某个整数值。使用简单的 if(),您可以设置在所有情况下您喜欢的“回退”值 NaN 返回 :-)。W3 还在这里声明 NaN 的全局版本将在检查之前进行类型转换,这提供了一些额外的证明(Number.isNaN() 不这样做)。发送到服务器/后端的任何值仍应在那里进行验证!