如何在html文本字段中限制数字的最大值和最小值
问题描述:
我有一个文本字段,应允许用户输入数字,最大长度应为2,最大值应为31,最小值应为1
我能够前2个条件但不知道最后2个条件
I have a text field which should allow the user to enter numbers,the maximum length should be 2 and the maximum value should be 31 and minimum value should 1 I am able to first 2 conditions but dont know the last 2 conditions
有人可以帮助我吗?
<input type="text" name = "ccdate" class="form-control" maxlength="2" onkeypress="return isNumber(event)" >
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;
}
NOte 我不想使用HTML5输入类型=数字
NOte I dont want to use HTML5 input type="number"
答
试试这个(Purely Jquery方法):
Try this(Purely Jquery approach):
HTML:
<input type="text" name = "ccdate" class="form-control" maxlength="2">
<div id="div1"></div>
JQUERY:
$('[name="ccdate"]').keyup(function(){
if(parseInt($(this).val()) > 31){
$('#div1').html('value cannot be greater then 31');
$(this).val('');
}
else if(parseInt($(this).val()) < 1)
{
$('#div1').html('value cannot be lower then 1');
$(this).val('');
}
else
{ $('#div1').html(''); }
});
编辑: - (根据提问评论检查用户输入的字符串或数字):
EDIT :-(as per questioner comment to check user entered string or number):
$('[name="ccdate"]').keyup(function(){
if(isNaN($(this).val()))
{
$('#div1').html('entered string');
$(this).val('');
}
else if(parseInt($(this).val()) > 31){
$('#div1').html('value cannot be greater then 31');
$(this).val('');
}
else if(parseInt($(this).val()) < 1)
{
$('#div1').html('value cannot be lower then 0');
$(this).val('');
}
else
{ $('#div1').html(''); }
});
编辑: - (纯Javascript方法) (只需在文本框中提供一个唯一的 id
说't1'
)
EDIT :- (Pure Javascript approach)(Just provide a unique id
to your textbox say 't1'
)
document.getElementById('t1').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 1 || parseInt(this.value) > 31 || isNaN(this.value)) ? "" : (this.value)
});