Ajax提交之前的jQuery表单验证

前端之家收集整理的这篇文章主要介绍了Ajax提交之前的jQuery表单验证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
JavaScript位:
  1. $(document).ready(function()
  2. {
  3. $('#form').submit(function(e)
  4. {
  5.  
  6. e.preventDefault();
  7. var $form = $(this);
  8.  
  9. // check if the input is valid
  10. if(! $form.valid()) return false;
  11. $.ajax(
  12. {
  13. type:'POST',url:'add.PHP',data:$('#form').serialize(),success:function(response)
  14. {
  15. $("#answers").html(response);
  16. }
  17. });
  18.  
  19. })
  20. });

HTML位:

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

所以这是我试图使用的代码。这个想法是在我用Ajax发送表单之前,让我的所有输入都被验证。我已经尝试了许多这样的版本,但每次我最终提交即使表单没有完全填写。我所有的输入都是“必需”类。谁能看到我做错了什么?

此外,我依赖于基于类的需求,因为我的输入名称是用PHP生成的,所以我永远不能确定什么名字[id]或输入类型。

我在“页面”中显示/隐藏问题。

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

JS:

  1. function toggleVisibility(newSection)
  2. {
  3. $(".section").not("#" + newSection).hide();
  4. $("#" + newSection).show();
  5. }
您可以使用 submitHandler选项。基本上将$ .ajax调用放在此处理程序中,即将其与验证设置逻辑反转。
  1. $('#form').validate({
  2.  
  3. ... your validation rules come here,submitHandler: function(form) {
  4. $.ajax({
  5. url: form.action,type: form.method,data: $(form).serialize(),success: function(response) {
  6. $('#answers').html(response);
  7. }
  8. });
  9. }
  10. });

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

猜你在找的Ajax相关文章