我有一个文本字段,应允许用户输入数字,最大长度应为2,最大值应为31,最小值应为1我能够执行前2个条件,但不知道后2个条件
有人可以帮我吗?
<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;
}
注意我不想使用HTML5输入type =“ number”
试试这个(纯Jquery方法):
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(''); }
});
编辑:-(根据发问者的注释来检查用户输入的字符串或数字):
$('[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'
)
document.getElementById('t1').addEventListener('keyup', function(){
this.value = (parseInt(this.value) < 1 || parseInt(this.value) > 31 || isNaN(this.value)) ? "" : (this.value)
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句