我有这个 JQuery 函数:
function CheckRequired(event) {
var $form = $(this);
var emptyElements = $form.find('.required').filter(function() {
return this.value === ''
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
return false;
}
}
我使用另一个函数调用此函数:
$(document).ready(function () {
$('form').on('submit', CheckRequired);
});
因此它将在所有表单上调用
它检查具有 required
类的表单元素
然后我在 PHP 中得到了这个:
if($_POST) {
}
检查已发布的表单(每个页面都有)
但是return false
并没有阻止表单的发布
更新:
表单提交按钮如下所示:
<input type="submit" name="submit" id="submit" value="Save" onclick="SubmitForm('#form1', '<?php echo $Settings_PathName; ?>/<?php echo $Settings_PagesPath; ?>/companies/customers/company.php?customer=<?php echo $customer["sequence"]; ?>', '.EditCustomer');" class="btn btn-default" />
函数SubmitForm
是:
function SubmitForm(form, postaction, div_name) {
CheckRequired();
$(form).submit(function(event){
event.preventDefault()
//$('#LoadingDiv').show();
var data = $(this).serialize();
$.post(postaction, data)
.success(function(result){
console.log(result);
//$('#LoadingDiv').hide();
$( div_name ).html(result);
$("html, body").animate({ scrollTop: 0 }, "slow");
})
.error(function(){
$( div_name ).html('Error Loading Page');
$("html, body").animate({ scrollTop: 0 }, "slow");
console.log('Error loading page');
console.log(result);
})
return false;
});
}
所以表单位于 company.php
上,它是从 customers.php
customers.php
有以下代码:
$(document).ready(function() {
$('.EditCustomer').load("<?php echo $Settings_PathName;?>/<?php echo $Settings_PagesPath; ?>/companies/customers/company.php?customer=<?php echo $_GET["seq"]; ?>");
});
因此表单无需刷新主页即可提交,只需使用 jquery 重新加载即可
最佳答案
你可以这样调用它:
$('form').submit(CheckRequired);
或者你可以看到:
你的函数中的$(this)
不是你想象的那样,它是 window 对象。您必须在函数调用中传递上下文:
function CheckRequired(event, el) {
var $form = $(el); // <---pass the context element here
var emptyElements = $form.find('.required').filter(function() {
return this.value.trim() === ''; //<-----should trim the value.
});
if(emptyElements.length > 0) {
event.preventDefault();
emptyElements.addClass("EmptySelect").attr('title', 'This field is required');
//alert(emptyElements.attr("id"));
alert("One or more fields cannot be blank");
// return false; // it is not needed as you are using event.preventDefault();
}
}
然后你可以这样调用它:
$('form').submit(function(){
CheckRequired(this);
});
关于javascript - JQuery 返回 false 不停止执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32605642/