Possible Duplicate:
How to allow only numeric (0-9) in HTML inputbox using jQuery?可能的副本:如何使用jQuery在HTML inputbox中只允许数值(0-9)?
How to allow only numbers to be written in this textbox ?
如何只允许在这个文本框中写入数字?
<input type="text" class="textfield" value="" id="extra7" name="extra7">
3 个解决方案
#1
189
You could subscribe for the onkeypress event:
您可以订阅onkeypress事件:
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
and then define the isNumber
function:
然后定义isNumber函数:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
You can see it in action here.
你可以在这里看到它的作用。
#2
28
With HTML5 you can do
通过HTML5你可以做到
<input type="number">
You can also use a regex pattern to limit the input text.
您还可以使用regex模式来限制输入文本。
<input type="text" pattern="^[0-9]*$" />
#3
13
You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0"
).
您还可以使用一些HTML5属性,一些浏览器可能已经利用了它们(type="number" min="0")。
Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.
无论您做什么,请记住在服务器端重新检查您的输入:您永远不能假定已经执行了客户端验证。
#1
189
You could subscribe for the onkeypress event:
您可以订阅onkeypress事件:
<input type="text" class="textfield" value="" id="extra7" name="extra7" onkeypress="return isNumber(event)" />
and then define the isNumber
function:
然后定义isNumber函数:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
You can see it in action here.
你可以在这里看到它的作用。
#2
28
With HTML5 you can do
通过HTML5你可以做到
<input type="number">
You can also use a regex pattern to limit the input text.
您还可以使用regex模式来限制输入文本。
<input type="text" pattern="^[0-9]*$" />
#3
13
You also can use some HTML5 attributes, some browsers might already take advantage of them (type="number" min="0"
).
您还可以使用一些HTML5属性,一些浏览器可能已经利用了它们(type="number" min="0")。
Whatever you do, remember to re-check your inputs on the server side: you can never assume the client-side validation has been performed.
无论您做什么,请记住在服务器端重新检查您的输入:您永远不能假定已经执行了客户端验证。