我创建了一个输入文本框的验证,它只接受数字值,也只接受8位数字,但它在Safari和Internet Explorer上不起作用。有人可以帮我把它弄好吗?
$("#user_phone").keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input maxlength="8" type="text" class="form-control" placeholder="Mobile eg 99999999" name="user_phone" id="user_phone" required>
注意:如果任何语法错误只是忽略它。必须由复制粘贴引起。
答案 0 :(得分:2)
尝试使用此代码:
<script>
$('#user_phone').keypress(function(e){
var phone = $(this).val();
if(phone.length >= 8){
alert('Not more the 8 char');
return false;
}
var key_codes = [48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 0, 8];
if (!($.inArray(e.which, key_codes) >= 0)) {
e.preventDefault();
}
})
</script>
答案 1 :(得分:0)
$("#user_phone").keydown(function (e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 ||(e.keyCode === 65 && (e.ctrlKey === true || e.metaKey === true)) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
"let it happen, don 't do anything";
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
}
);
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input maxlength="8" type="text" class="form-control" placeholder="Mobile eg 99999999" name="user_phone" id="user_phone" required>
&#13;