我有这个 html 和 jquery 代码,可以提醒用户只输入数字。 我想在用户输入点“。”时提醒用户在文本字段中。
<html>
<body>
<div class="form-group" id="parentID">
<input class="form-control" placeholder="ID Number (10 max numbers)" id="childID" name="idnumber" type="text" maxlength="10" required autofocus>
<span id="checkID"></span>
</div>
</body>
<script>
var ID = $("#childID").val();
if (ID.indexOf(".") != -1) {
$("#checkID").html("ID number must contain numbers only");
$("#checkID").css("color", "orange");
}
$(document).ready(function() {
$("#childID").keyup(checkPasswordMatch);
});
//In this function it will disable special characters in user input but still accepts the '.' and '>' character type, what keycode is it to disable that 2 character?
$(function() {
$('#parentID').on('keydown', '#childID', function(e) {-1 !== $.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) || /65|67|86|88/.test(e.keyCode) && (!0 === e.ctrlKey || !0 === e.metaKey) || 35 <= e.keyCode && 40 >= e.keyCode || (e.shiftKey || 48 > e.keyCode || 57 < e.keyCode) && (96 > e.keyCode || 105 < e.keyCode) && e.preventDefault() });
})
</script>
</html>
我希望在输入字段检测到 keyup 上的点时出现 span id="checkID"。我尝试使用 indexOf() 但 span 标签不会出现。谁能帮我?
最佳答案
我已经用 fiddle 更新了你的代码。请在下面的 fiddle 链接中找到更新的代码。刚刚添加了一项功能并更新了 keyup 和 keypress 事件。
$(function() {
$('#parentID').on('keypress keyup', '#childID', function(e) {
if(isNumber(e)){
$("#checkID").html("");
} else{
//e.preventDefault();
$("#checkID").html("ID number must contain numbers only");
$("#checkID").css("color", "orange");
}
});
});
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode <= 46 || charCode > 57)) {
return false;
}
return true;
}
参见 Demo
显示错误信息。如果您不想允许其他字符,请取消注释//e.preventDefault();
关于javascript - 如何提醒用户输入类型文本在用户输入时检测到点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39137816/