Validate a form with jQuery Validator plugin but trigger it from a link

放肆的年华 提交于 2019-12-08 12:08:30

问题


All, I'm trying to use the jQuery Form Validator (http://docs.jquery.com/Plugins/Validation). However I'd like to be able to click a link to do the validation and then submit the form if everything is ok. Does anyone know how to do this? Any tips or suggestions would be greatly appreciated.

Thanks!


回答1:


Totally possible. The plugin docs even give an example, which I've modified a little bit to submit instead of alert:

$("#myform").validate();
$("a.check").click(function() {
  if ($("#myform").valid()) {
    $("#myform").submit();
  }
  return false;
});



回答2:


This code will work the same as the accepted answer but with all the redundancy removed. (There is no need to use .valid() to check the form, since the Validate plugin will continue to properly block an invalid form.)

  • Use event.preventDefault() to block the default behaviors of the anchor element.

    $("#myform").validate();                // initialize plugin
    
    $("a#submit").on('click', function(e) { // capture the anchor link click
        e.preventDefault();                 // block default anchor link behaviors
        $("#myform").submit();              // simulates a submit button
    });
    
  • Use an href="#" within the anchor tag.

    <a id="submit" href="#">Submit</a>
    

$(document).ready(function() {

  $("#myform").validate({ // initialize plugin
    submitHandler: function(form) { // simulate form submission for demo
      alert('form submission');
      return false;
    }
  });

  $("a#submit").on('click', function(e) { // capture the anchor link click
    e.preventDefault();                 // block default anchor link behaviors
    $("#myform").submit();              // simulates a submit button
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.js"></script>

<form id="myform">
  <input type="text" required="required" name="test1" />
  <br />
  <input type="text" required="required" name="test2" />
  <br />
  <a id="submit" href="#">Submit</a>
</form>


来源:https://stackoverflow.com/questions/8681853/validate-a-form-with-jquery-validator-plugin-but-trigger-it-from-a-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!