我有一个textbox
,我希望用户在其中添加整数,并且位数不能少于10
。
这里的问题是,即使单击确定,alert
消息仍在不断触发。请提出代码有什么问题。还建议是否还有其他好的方法来实现这一点
function checkLength(el) {
if (el.value.length != 10 || el.getAttribute('data-should-alert') === 'false') {
alert("Minimum 10 numbers are accepted");
el.setAttribute('data-should-alert', 'false');
el.focus();
} else {
el.setAttribute('data-should-alert', 'true');
}
}
function IsNumeric4(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error4").style.display = ret ? "none" : "inline";
return ret;
}
<div class="form-group">
<label for="">Stores / Sites Asst. Manager Mob</label>
<input type="text" class="form-control" id="txtStoreSiteAsstMangrMob" maxlength="10" onblur="checkLength(this)" onkeypress="return IsNumeric4(event);" ondrop="return false;" onpaste="return false;" />
<span id="error4" style="color: Red; display: none">* Only numbers allowed (0 - 9)</span>
</div>
答案 0 :(得分:3)
问题是 onblur 事件总是在元素失去焦点时触发
所以一种解决方案是将事件更改为 onchange 事件,而不是 onblur
from flask.globals import _request_ctx_stack
def get_domain():
fragments = [
_request_ctx_stack.top.url_adapter.url_scheme,
_request_ctx_stack.top.url_adapter.get_host(''),
]
return '://'.join(fragments)
function checkLength(el) {
if (el.value.length != 10 || el.getAttribute('data-should-alert') === 'false') {
alert("Minimum 10 numbers are accepted");
el.setAttribute('data-should-alert', 'false');
el.focus();
} else {
el.setAttribute('data-should-alert', 'true');
}
}
function IsNumeric4(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error4").style.display = ret ? "none" : "inline";
return ret;
}
答案 1 :(得分:0)
我认为问题在于显示警报后您正在集中精力
答案 2 :(得分:0)
因为警报将再次触发模糊。
setTimeout
为您提供了一种在.focus()
之后拨打alert
的棘手方法:
function checkLength(el) {
// this may cause once alert, it will always alert
if (el.value.length != 10/* || el.getAttribute('data-should-alert') === 'false'*/) {
alert("Minimum 10 numbers are accepted");
el.setAttribute('data-should-alert', 'false');
// set this
setTimeout(function(){
el.focus();
}, 10);
} else {
el.setAttribute('data-should-alert', 'true');
}
}
function IsNumeric4(e) {
var keyCode = e.which ? e.which : e.keyCode
var ret = ((keyCode >= 48 && keyCode <= 57) || specialKeys.indexOf(keyCode) != -1);
document.getElementById("error4").style.display = ret ? "none" : "inline";
return ret;
}
<div class="form-group">
<label for="">Stores / Sites Asst. Manager Mob</label>
<input type="text" class="form-control" id="txtStoreSiteAsstMangrMob" maxlength="10" onblur="checkLength(this)" onkeypress="return IsNumeric4(event);" ondrop="return false;" onpaste="return false;" />
<span id="error4" style="color: Red; display: none">* Only numbers allowed (0 - 9)</span>
</div>