Jquery onclick validation

I have a problem with a jquery validation plugin that doesn't make sense to me. 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 is never validated, or at least the .valid() function always returns true, but I don’t understand why? I have used the validate plugin for many years, but not in this context.

+4
source share
4 answers

I decided 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 } }); }); 
+5
source

If you have a link and you need to confirm the form. This function also goes to the next tab in the user interface tabs, checking each tab with a form on 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; } }); 
+7
source

You are trying to attach an event to an element that is not yet displayed

you need to use ready onDOM

 $(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 number 1 : always think that the DOM should be presented before the pix of the code you write is the most common mistake on this site ...

You can read this advice and much more on the jquery tag on this site, read it

+4
source

You need to put your check on the "finished documentation"

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

Source: https://habr.com/ru/post/1394610/


All Articles