【发布时间】:2018-10-30 13:59:04
【问题描述】:
我正在尝试在使用 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 请求。您可能应该重新考虑这一点,并在验证所有输入后提出一个请求
-
我明白你的意思。我没有想到我的括号要去哪里。我只想要一个ajax调用。感谢您指出这一点!
标签: jquery validation input each