在文本输入按键上我想显示没有任何插件的验证错误。 我正在尝试编写一个通用的jQuery函数,我可以在任何页面中使用它。 错误弹出应该是动态的。
function checkno(txt,e) {
$(txt).keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (!document.getElementById('spanmsg')) {
$(txt).after("<span id='spanmsg' class='fixed'>This is wrong input</span>")
$('#spanmsg').show(0).delay("500").hide(0);
txt.value = '';
}
else {
$('#spanmsg').show(0).delay("500").hide(0);
txt.value = '';
}
return false;
}
});
}
答案 0 :(得分:0)
而是尝试使用keyup方法:
$(theElement).keyup(function() {
var $th = $(this);
$th.val( $th.val().replace(/[^0-9]/g, function(str) { alert('You typed " ' + str + ' ".\n\nPlease use only numbers.'); return ''; } ) );
});
希望这有帮助。
答案 1 :(得分:0)
我已将整个代码放在下面,
<html>
<head>
<title>Please Rate if it helps</title>
<!-- PUT A PATH OF JQUERY LIBRARY -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script>
window.onload = function () {
$("#txt").keypress(function (e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (!$(txt).next().hasClass("spanmsg")) {
var error = $("<div class='spanmsg'>This is wrong input</div>");
$(txt).after(error);
$(error).css({
top: ($(txt).position().top + 1) + "px",
left: ($(txt).position().left + 1) + "px",
width: $(txt).width() + "px",
height: $(txt).height() + "px"
});
}
$(this).next().show(0).delay("500").delay(500, function () {
$(this).remove();
});
this.value = '';
return false;
}
});
}
</script>
<style>
.spanmsg {
position: absolute;
text-align: center;
color: red;
}
</style>
</head>
<body>
<input type="text" id="txt">
</body>
</html>
如果它对你有帮助......
答案 2 :(得分:0)
只需使用您更新的代码,无需其他框架。在JSFiddle上运行。
function checkno(txt,e) {
//if the letter is not digit then display error and don't type anything
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {
if (!document.getElementById('spanmsg')) {
$(txt).after("<span id='spanmsg' class='fixed'>This is wrong input</span>")
$('#spanmsg').show(0).delay("500").hide(0);
txt.value = '';
}
else {
$('#spanmsg').show(0).delay("500").hide(0);
txt.value = '';
}
return false;
}
}
$('#txt').keyup(function (e) {
checkno(this,e);
});