【发布时间】:2019-12-11 01:10:41
【问题描述】:
我必须使用 Jquery 验证一个表单,作为我本周日作业的一部分。我需要检测一个字段是否为空并阻止表单输入,同时还将错误消息放入 id 为“divMessage”的 div 中。我想动态地执行此操作,但注意到我为字段检索的值始终为零。我不知道该怎么办,我很恐慌。如果我能正确理解这一点,我就可以自己完成剩下的作业。
尝试使用 $("username).val() 验证输入文本字段的值(一个字段的示例,“用户名”,如下所示),但结果始终为 0 。我很茫然。我有简化了下面的表单,以减少故障排除的混乱。
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Add Movie Form</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$(document).ready(function () {
var name = $("#username").val()
error_username= false;
// Prevention of form submission
$("#addMovieform").submit(function () {
if (error_username=false){
return false;
} else {return true;
}
});
//Dynamically add errorMessage in divMessage
$("#username").focusout(function () {
if (name.length == 0) {
errorList.append("<li>Your name is required</li>")
$("li").eq(0).attr("class", "name_error_1");
} else {
// Remove error message when name has been typed
$(".name_error_1").remove()
}
})
});
<script>
<body>
<div id="divMessage"></div>
<table id="formtable">
<colgroup>
<col style="width: 20%;">
</colgroup>
<form action="/action_page.php" id="addMovieform" method="POST">
<!-- Username -->
<tr>
<td><label for="username">Name</label></td>
<td><input type="text" name="movie-username"id="username"
placeholder="Your Name"></td>
</tr>
</form>
</table>
</body>
</head>
希望在用户名字段为空时在“divMessage”中动态插入带有消息的项目符号,然后在用户名字段不再为空时删除项目符号。
【问题讨论】:
标签: jquery html validation input event-handling