gpt4 book ai didi

Ajax 提交之前的 jQuery 表单验证

转载 作者:行者123 更新时间:2023-12-03 21:28:18 25 4
gpt4 key购买 nike

JavaScript 位:

$(document).ready(function()
{
$('#form').submit(function(e)
{

e.preventDefault();
var $form = $(this);

// check if the input is valid
if(! $form.valid()) return false;
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});

})
});

HTML 位:

    <input type="text" name="answer[1]" class="required" />
<input type="text" name="answer[2]" class="required" />

这就是我尝试使用的代码。我的想法是在使用 Ajax 发送表单之前验证所有输入。我现在已经尝试了很多版本,但每次我最终都会提交,即使表格没有完全填写。我的所有输入都是“必需”类别的。谁能看出我做错了什么吗?

此外,我依赖于基于类的要求,因为我的输入名称是使用 php 生成的,因此我永远无法确定我得到的名称[id] 或输入类型。

当我在“页面”中浏览问题时,我会显示/隐藏问题。

<input type="button" id="next" onClick="toggleVisibility('form3')" class="next-btn"/>

JS:

function toggleVisibility(newSection) 
{
$(".section").not("#" + newSection).hide();
$("#" + newSection).show();
}

最佳答案

您可以使用submitHandler选项。基本上将 $.ajax 调用放入此处理程序中,即使用验证设置逻辑反转它。

$('#form').validate({

... your validation rules come here,

submitHandler: function(form) {
$.ajax({
url: form.action,
type: form.method,
data: $(form).serialize(),
success: function(response) {
$('#answers').html(response);
}
});
}
});

如果验证通过,jQuery.validate 插件将调用提交处理程序。

关于Ajax 提交之前的 jQuery 表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11469616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com