我的个人资料页面上有几种表格。每个表单都有其自己的提交按钮。当用户单击“提交”按钮时,我希望该按钮消失并显示一个微调框。
那很好。我遇到的问题是,如果用户忘记填写必填字段,则按钮不会返回可见。微调框保持可见。而且该页面必须重新加载。
jQuery不会拦截表单提交(尽管我可以解决表单提交问题),但它只是切换微调器和按钮可见性。
有帮助吗?
$("#profile-loading").hide();
$("#social-loading").hide();
$(document).ready(function () {
$("#btn_profile").on("click", function (e) {
$("#profile-loading").show();
$("#btn_profile").hide();
checkForm('#formProfile', "#btn_profile", "#profile-loading");
});
$("#btn_social").on("click", function (e) {
$("#social-loading").show();
$("#btn_social").hide();
checkForm('#formSocialMedia', "#btn_social", "#social-loading");
});
});
//Check the passed in form and toggle the buttons and the loading spinner
function checkForm($formid, $buttonid, $spinnerid) {
var emptyFields = $('#formProfile .required').filter(function () {
return $(this).val() === "";
}).length;
if (emptyFields === 0) {
console.log("no emptyFields");
} else {
console.log("emptyFields");
return false;
}
//I tried looping through each form field, but can't seem to get the form targeted.
// $($formid + '.required').each(function () {
// console.log("checkForm");
//
// var self = $(this)
// if (self.val() === '') {
// // empty
// console.log("empty");
// } else {
// // not empty
// console.log("NOT empty");
// }
// });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="somelink" id="formProfile">
<input id="name" name="name" type="text" required="required">
<input id="url" name="url" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="profile-loading"></i>
<button id="btn_profile" type="submit">Save Changes</button>
</form>
<form method="post" action="someotherlink" id="formSocialMedia>
<input id="facebook" name="facebook" type="text" required="required">
<input id="instagram" name="instagram" type="text" required="required">
<i class="fas fa-spinner fa-2x fa-spin" id="social-loading"></i>
<button id="btn_social" type="submit">Save Changes</button>
</form>
答案 0 :(得分:2)
您的代码有几个问题,但最重要的是,您正在使用required
类来检索所需的表单元素,该类似乎未在html中使用。相反,您可以使用类似
$('#formProfile [required]')
返回具有formProfile
属性的required
的所有子元素。您还有另一个问题,就是表单的ID是硬编码的。不用硬编码,而使用变量$formid
。
$($formid + ' [required]')
答案 1 :(得分:0)
尝试重新排序脚本,首先进行验证,然后检查是否通过。确保checkForm
返回true
(如果有效)。
$("#btn_profile").on("click", function (e) {
if (checkForm('#formProfile', "#btn_profile", "#profile-loading")) {
$("#profile-loading").show();
$("#btn_profile").hide();
}
});
$("#btn_social").on("click", function (e) {
if (checkForm('#formSocialMedia', "#btn_social", "#social-loading")) {
$("#social-loading").show();
$("#btn_social").hide();
}
});