javascript 使用javascript指定要在数字字段中输入的数字范围
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5193278/
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
Specify range of numbers to input in number field using javascript
提问by watkib
I have a field ' sessionid' of type text in an html form. I want the user to enter only numbers ranging 1-12 and no more. if 0 or 13 e.t.c is entered an error is returned.
我在 html 表单中有一个文本类型的字段“ sessionid”。我希望用户只输入 1-12 之间的数字,不要再输入了。如果输入 0 或 13 等,则返回错误。
Here's the html form
这是html表单
Session Id
</td>
<td>
<input type="text" name="session id" />
Thanks.Please Help.
谢谢。请帮助。
回答by chiborg
Try converting the number to an int:
尝试将数字转换为 int:
<script type="text/javascript">
function checksession(sess){
var i = parseInt(sess);
if(isNaN(c) || c < 1 || c > 12){
alert("Invalid session id!");
}
}
</script>
For modern browsers, I'd recommend to use the HTML5 numberinput type:
对于现代浏览器,我建议使用 HTML5number输入类型:
<input type="number" name="sessionid" min="0" max="12" >
回答by Tom Gullen
Easiest way would be use a select field
最简单的方法是使用选择字段
<select name="number-chooser">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">Three</option>
<option value="4">4</option>
</select>
This is fine for small number spaces, but if you are going a lot bigger REGEXP is your friend.
这对于小数字空间很好,但如果你要大得多,那么 REGEXP 就是你的朋友。
回答by Tunca Ersoy
You can use regular expressions.
您可以使用正则表达式。
http://www.javascriptkit.com/javatutors/re.shtml
http://www.javascriptkit.com/javatutors/re.shtml
http://www.regular-expressions.info/numericranges.html
http://www.regular-expressions.info/numericranges.html
<script language="JavaScript1.2">
function checkpostal(){
var regexp=/^([1-9]|10|11|12)$/ //regular expression
if (document.myform.sessionid.value.search(regexp)==-1) //if match failed
alert("wrong input")
}
</script>
<form name="myform">
<input type="text" name="sessionid">
<input type="button" onClick="checkpostal()" value="check">

