我正在尝试使用 JQuery 使表单动态化,当用户在表单的第二输入中输入少于 4 个字符时,我想显示一条错误消息及其颜色。
这是我的代码:
<form>
<label for="text">Text </label>
<input id="text" type="text">
<label for="text2">Text 2</label>
<input id="text2" type="text">
<button type="submit">Send</button>
<div class="alert alert-block alert-danger" style="display:none">
<h4>Error!</h4>
You have to enter less than 4 caracters in the 2nde input !
</div>
</form>
<script src="bootstrap/js/jquery.js"></script>
<script>
$(function(){
$("form").on("submit", function() {
if($("input:text2").val().length < 4) {
$("div.form-group").addClass("has-error");
$("div.alert").show("slow").delay(4000).hide("slow");
return false;
}
});
});
</script>
但似乎只有当第一个输入的值小于 4 个字母时才会出现错误消息,但我希望它在第二个输入的值小于 4 个字母时出现。
谢谢
最佳答案
而不是:
$("input:text2");
您的意思是:
$("#text2")
?我不确定前者是什么意思,但后者是第二个文本输入 ID 的 ID 选择器。
关于javascript - 在JQuery中,如何仅根据一个表单输入的值显示错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451785/