[英]Validating input type numbers using javascript / jQuery
I have a input box and need to accept just numbers. 我有一个输入框,只需要接受数字。
I use javascript
and it works fine but the problem : when the box is empty or deleting numbers it returns false and the box color get red. 我使用
javascript
它工作正常,但问题是:当框为空或删除数字时,它返回false,框颜色变为红色。
Here is the codes: 这是代码:
<input id="amount" type="number" size="7" name="amount" onkeypress='return isNumberKey(event)' required/>
<script type="text/javascript">
function isNumberKey(evt){
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
check it this validation code : http://jsbin.com/ImIruPEf/1/edit 检查一下这个验证码: http : //jsbin.com/ImIruPEf/1/edit
$(document).ready(function(){
$("#Submit").click(function(e){
var isNumber = IsNumberOnly('input#Age');
if(!isNumber)
{
e.preventDefault();
$("#ErrorMessage").text('Invalid value. Please enter numeric value.');
}
else
{
$("#ErrorMessage").text('Success.');
}
});
});
function IsNumberOnly(element) {
var value = $(element).val();
var regExp = "^\\d+$";
return value.match(regExp);
}
<script type="text/javascript">
function demoMatchClick() {
var re = new RegExp("^[0-9]+$");
var val=document.GetelementByID("amount").value;
if (val.match(re)) {
alert("Successful match");return true;
} else {
alert("No match"); return false;
}
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.