JQuery:如何在发送表单之前执行代码

JQuery: how to execute code before sending a form

本文关键字:表单 执行 代码 JQuery      更新时间:2023-09-26

我制作了一个表单并将其 attr 设置为 onsubmit="return false"

现在我需要在实际提交之前执行一些操作,如下所示:

$('input[name=submit]').click(function(){
    $('.switch-input').attr('checked','checked');//getting all values of chbz
    //here goes a little more code//
    $('form[name=setform]').removeAttr('onsubmit');//finally sending to $_POST
});

乍一看一切正常,但我想知道它会在发送前 100% 执行所有代码还是我做错了?

onsubmit="return false" 属性将阻止表单像往常一样提交。但是,当用户单击"提交"输入时,上述代码段将执行一次,删除onsubmit属性并使表单能够正常提交,但用户必须再次单击"提交"才能提交。

您可以保留现有的代码段,并告诉 jQuery 通过 .submit() 方法的第三个变体显式提交表单:

$('input[name=submit]').click(function(){
    $('.switch-input').attr('checked','checked');//getting all values of chbz
    //here goes a little more code//
    $('form[name=setform]').removeAttr('onsubmit');//make the form submittable
    $('form[name=setform]').submit();//finally sending to $_POST
});

或者,您可以删除 onsubmit="return false" 属性,并使用该方法的.submit(handler)变体,这简化了代码并保证处理程序将在提交表单之前执行:

$('form[name=setform]').submit(function(){
    $('.switch-input').attr('checked','checked');//getting all values of chbz
    //here goes a little more code//
});

您可以考虑关闭 onsubmit 属性,而是使用您的.click()代码,并在末尾输入 return false。您也可以按照 Stiliyan 的建议使用.submit()