jquery validation onclick

限于喜欢 提交于 2019-12-18 13:23:15

问题


I have an issue with the jquery validate plugin that doesn't make sense to me. Please can anyone see where my mistake is?

Here is my HTML:

<form id="form">
   <input type="text" name="name" class="required" />
   <input type="text" name="email" class="required email" />
</form>
<a id="link">Save</a>

Here is my JS

<script src="jquery 1.7.1"></script>
<script src="jquery.validate.1.9"></script>
<script>
    $('#link').click(function()
    {
        $('#form').validate();
        if ($('#form').valid()) // check if form is valid
        {
            // do some stuff
        }
        else 
        {
            // just show validation errors, dont post
        }
    });

</script>

The form never gets validated or at least the .valid() function always returns true but I can't see why? I used the validate plugin for years but not in this context.


回答1:


If you have a link and need to validate a form. Also this function goes to next tab in UI Tabs validating each tab with a form in each tab.

$('.next-tab').click(function() { 
    //if form is valid
    if ($("#frmSignup").valid()) {
        //activate next tab
        $('#signuptabs').tabs('enable', $(this).attr("rel"));
        //switch to next tab
        $tabs.tabs('select', $(this).attr("rel"));
        return false;
    }
});



回答2:


You are trying to attach an event to an element which isn't rendered yet

you have to use the onDOM ready

$(function() {
     $('#link').click(function(){
        $('#form').validate();
        if ($('#form').valid()) // check if form is valid
        {
            // do some stuff
        }
        else 
        {
            // just show validation errors, dont post
        }
    });
});

$(functionHandler) == $(document).ready(functionHandler);

Rule No.1: Always think, is the DOM must be rendered before that peice of code that you write, It's the most common mistake on this site...

This tip and many more you can read on the jquery tag on this site, read it




回答3:


Solved it for now. Now the validator does what I want. JS below, same HTML:

$(function() 
{ 
   $('#link').click(function() 
   { 
      if ($("input[name=name]").valid() && $("input[name=email]").valid()) 
      { 
         // do some stuff 
      } 
      else 
      { 
         // just show validation errors, dont post 
      } 
   }); 
});



回答4:


You need to put your validation in an "on document ready"

$(document).ready(function(){
    $('#form').validate();
});


来源:https://stackoverflow.com/questions/9129029/jquery-validation-onclick

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