如何使HTMLinput标签只接受数值?

我需要确保某个<input>字段只将数字作为值。 input不是表单的一部分。 因此它没有被提交,所以在提交期间validation是不可行的。 我希望用户无法input数字以外的任何字符。

有没有一个干净的方式来实现这一目标?

您可以使用HTML5inputtypes编号来限制数字条目:

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

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

<!DOCTYPE html>

另请参阅https://github.com/jonstipe/number-polyfill ,以获得旧版浏览器的透明支持。

对于一般的目的,你可以有JSvalidation如下:

 function isNumberKey(evt){ var charCode = (evt.which) ? evt.which : event.keyCode if (charCode > 31 && (charCode < 48 || charCode > 57)) return false; return true; } <input name="someid" type="number" onkeypress="return isNumberKey(event)"/> 

如果你想允许小数点,用这个replace“if条件”:

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

来源: HTML文本input只允许数字input

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

您也可以在html5中使用模式属性:

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

http://www.pageresource.com/html5/input-validation-tutorial/

虽然,如果您的DOCTYPE不是html那么我认为您将需要使用一些JavaScript / jQuery的。

您可以使用<input type="number" /> 。 这将只允许在input框中input数字。

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

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

对于Firefox,你可以使用javascriptvalidationinput:

http://jsfiddle.net/VmtF5/

 function AllowOnlyNumbers(e) { e = (e) ? e : window.event; var key = null; var charsKeys = [ 97, // a Ctrl + a Select All 65, // A Ctrl + A Select All 99, // c Ctrl + c Copy 67, // C Ctrl + C Copy 118, // v Ctrl + v paste 86, // V Ctrl + V paste 115, // s Ctrl + s save 83, // S Ctrl + S save 112, // p Ctrl + p print 80 // P Ctrl + P print ]; var specialKeys = [ 8, // backspace 9, // tab 27, // escape 13, // enter 35, // Home & shiftKey + # 36, // End & shiftKey + $ 37, // left arrow & shiftKey + % 39, //right arrow & ' 46, // delete & . 45 //Ins & - ]; key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode; //console.log("e.charCode: " + e.charCode + ", " + "e.which: " + e.which + ", " + "e.keyCode: " + e.keyCode); //console.log(String.fromCharCode(key)); // check if pressed key is not number if (key && key < 48 || key > 57) { //Allow: Ctrl + char for action save, print, copy, ...etc if ((e.ctrlKey && charsKeys.indexOf(key) != -1) || //Fix Issue: f1 : f12 Or Ctrl + f1 : f12, in Firefox browser (navigator.userAgent.indexOf("Firefox") != -1 && ((e.ctrlKey && e.keyCode && e.keyCode > 0 && key >= 112 && key <= 123) || (e.keyCode && e.keyCode > 0 && key && key >= 112 && key <= 123)))) { return true } // Allow: Special Keys else if (specialKeys.indexOf(key) != -1) { //Fix Issue: right arrow & Delete & ins in FireFox if ((key == 39 || key == 45 || key == 46)) { return (navigator.userAgent.indexOf("Firefox") != -1 && e.keyCode != undefined && e.keyCode > 0); } //DisAllow : "#" & "$" & "%" else if (e.shiftKey && (key == 35 || key == 36 || key == 37)) { return false; } else { return true; } } else { return false; } } else { return true; } } 
 <h1>Integer Textbox</h1> <input type="text" autocomplete="off" id="txtIdNum" onkeypress="return AllowOnlyNumbers(event);" /> 
 <input onkeyup="value=isNaN(parseFloat(value))?1000:value" type="number" value="1000" > 

onkeyup触发键释放时。

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

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

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

为了使它更加出类拔萃,你也可以有一个界限:

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

请享用!

如果你可以使用HTML5,你可以做<input type="number" />如果没有,你将不得不通过JavaScript来做到这一点,因为你说它不会被代码隐藏。

 <input id="numbersOnly" onkeypress='validate()' /> function validate(){ var returnString; var text = document.getElementByID('numbersOnly').value; var regex = /[0-9]|\./; var anArray = text.split(''); for(var i=0; i<anArray.length; i++){ if(!regex.test(anArray[i])) { anArray[i] = ''; } } for(var i=0; i<anArray.length; i++) { returnString += anArray[i]; } document.getElementByID('numbersOnly').value = returnString; } 

PS没有testing代码,但它应该是或多或less正确的,如果不检查错别字:D您可能想添加更多的东西,如该如何处理,如果string为空或空等。也可以使这个更快:D

我与这个战斗了一下。 这里和其他地方的许多解决scheme似乎很复杂 这个解决scheme使用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); }); 

在我的情况下,我跟踪最小值为1的小数量,因此input标签中的min =“1”,isNaN()检查中的abc = 1。 对于只有正数的数字,您可以将这些值更改为0,甚至可以简单地从input标签中删除min =“1”以允许使用负数。

此外,这适用于多个框(并可以节省你一些加载时间,通过单独做id),只需添加“validateNumber”类在需要的地方。

说明

parseInt()基本上做你所需要的,除了它返回NaN而不是一些整数值。 通过一个简单的if(),你可以设置所有NaN返回的情况下你喜欢的“fallback”值:-)。 此外,W3 在这里指出,NaN的全局版本将在检查之前进行types转换,从而给出一些额外的校对(Number.isNaN()不会这样做)。 发送到服务器/后端的任何值都应该在那里validation!

如何使用<input type="number"...>

http://www.w3schools.com/tags/tag_input.asp

此外,这里有一个问题,有一些使用Javascriptvalidation的例子 。

更新:链接到更好的问题(谢谢alexblum)。

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

在js中:

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

或者你可以写一个复杂的有用的方式:

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

注意 :跨浏览器和正则expression式的文字。

如果不是整数集0

 <input type="text" id="min-value" /> $('#min-value').change(function () { var checkvalue = $('#min-value').val(); if (checkvalue != parseInt(checkvalue)) $('#min-value').val(0); }); 

请使用JavaScript语言查看我的网页上的文本input元素的跨浏览器filter项目: input密钥filter 。 您可以将该值过滤为整数,浮点数或写入自定义filter(如电话号码filter)。 查看input一个整数的代码示例:

 <!doctype html> <html xmlns="http://www.w3.org/1999/xhtml" > <head> <title>Input Key Filter Test</title> <meta name="author" content="Andrej Hristoliubov anhr@mail.ru"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <!-- For compatibility of IE browser with audio element in the beep() function. https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible --> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css"> <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script> <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script> </head> <body> <h1>Integer field</h1> <input id="Integer"> <script> CreateIntFilter("Integer", function(event){//onChange event inputKeyFilter.RemoveMyTooltip(); var elementNewInteger = document.getElementById("NewInteger"); var integer = parseInt(this.value); if(inputKeyFilter.isNaN(integer, this)){ elementNewInteger.innerHTML = ""; return; } //elementNewInteger.innerText = integer;//Uncompatible with FireFox elementNewInteger.innerHTML = integer; } //onblur event. Use this function if you want set focus to the input element again if input value is NaN. (empty or invalid) , function(event){ inputKeyFilter.isNaN(parseInt(this.value), this); } ); </script> New integer: <span id="NewInteger"></span> </body> </html> 

接受的答案是:

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

这很好,但不完美。 它为我工作,但我得到一个警告,可以简化if语句。

然后看起来像这样,这是更漂亮的:

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

会评论原来的post,但我的声誉太低,这样做(只是创build此帐户)。

您可以使用属性type ='number'的<input>标签。

例如,您可以使用<input type='number' />

该input栏只允许数值。 您也可以指定该字段应该接受的最小值和最大值。

我使用这个邮政编码,快速和容易。

 <input type="text" id="zip_code" name="zip_code" onkeypress="return event.charCode > 47 && event.charCode < 58;" pattern="[0-9]{5}" required></input> 

在使用这段代码时,你不能在Mozilla Firefox中使用“BackSpace Button”,你只能在Chrome 47中使用退格&event.charCode <58;“pattern =”[0-9] {5}“required>

http://www.texotela.co.uk/code/jquery/numeric/ 数字input学分给LeoVũ提及这个,当然还有TexoTela。 与testing页面。

为了接受多个数字(不只是一个数字),最好在REGEX条件中加“+”:

<input type="text" name="your_field" pattern="[0-9]+">

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

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

它会正常工作。