我试图在使用 jQuery 提交之前检查一个或两个字段是否为空。如果任何输入为空,则应该提醒用户,否则转到 ajax 函数。如果我填写用户名字段,它不会查看密码字段。但是,如果我将用户名字段留空,则会显示正确的对话框,并且不会执行 ajax 脚本。我使用 .each() 函数是否错误?
HTML:
<div id="dialog_success" title="Success">
<p></p>
</div>
<div id="dialog_error" title="Error">
<p>If you see this text, check your jQuery.</p>
</div>
<div class="container">
<h2 class="form-heading">Create New User</h2>
<form id="insert_user_form" method="post" action="create_user.php" autocomplete="off">
<div class="container">
<label for="username">Username</label>
<input id="username_input" type="text" placeholder="Enter Username" name="username" autofocus>
<label for="password">Password</label>
<input type="password" placeholder="Enter Password" name="password">
<button id="create_user_btn" type="submit">Submit</button>
</div>
</form>
</div>
jQuery 和 ajax 的一部分:
$('#insert_user_form').submit(function (e) {
e.preventDefault();
$(':input').each(function () {
if ($(this).val() === "") {
$('#dialog_error').dialog("open");
$('.ui-widget-overlay').css({'background': 'red', 'opacity': '0.7'});
$('#dialog_error p').text("Please fill out all fields.");
return false;
}
else {
$.ajax({
type: 'POST',
//Begin the ajax
我也尝试过:
if($(this).length === 0)
但这仍然不起作用。
最佳答案
正如前面提到的,您应该在检查所有输入后进行 AJAX 调用。一种简单的方法是使用变量作为标志。
$('#insert_user_form').submit(function (e) {
e.preventDefault();
var isempty = false;
$(':input:not(button)').each(function () {
if ($(this).val() === "") {
$('#dialog_error').dialog("open");
$('.ui-widget-overlay').css({'background': 'red', 'opacity': '0.7'});
$('#dialog_error p').text("Please fill out all fields.");
isempty = true;
}
});
if(!isempty){
//Do your ajax
// ...
这样,如果所有输入都已填写,则变量 isempty
将为 false,如果至少有一个输入未填写,则为 true。
此外,$(':input')
还将捕获您拥有的 button
,因此您可以使用 :not
将其排除选择器。
关于jquery - 空输入返回 false 仅适用于一个输入,不适用于两个输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50439909/