Use jQuery Validation Plugin to Validate a Hidden Form

I wanted to share a tip with you regarding jQuery Validation Plugin. Of course we all love the plugin, but there might be a time when you might find yourself in a situation like this.

I recently added some functionality to my website. I added a page in the account section for members where they could see their personal information and could also edit the information if needed. I wanted to do keep all this information on one page. So when the page loads it shows member info and then if they click the edit button it turns into a form with input text fields. I wanted all this to be a good user experience so I turned to Ajax, when the button is clicked I wanted the account information area to disappear and the form to slide down which by default was hidden with CSS. This is where I found myself in bit of a problem. The markup for the form is added to the DOM when we click on the edit button but jQuery has no clue it’s there so the code below was not working.

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

Usually in a situation like this where an element is not part of the DOM when the page first loaded we use jQuery live() method e.g

$('#button').live('click', function(){
  //Do Something;
})
So how can we use this with jQuery validation plugin? See the below code:
$(document).ready(function(){

  $('#submitButton').live('click', function(){
     validateHiddenForm();
  })

  function validateHiddenForm (){
     $('#myForm').validate();
  }
});

So what I did above is I used the jQuery live() method on the button and then in the function I call the method which has the code to call the validation. That’s it!

Hope this will help someone if you stumble upon this post.

Important: As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers.

Leave a Reply

Your email address will not be published. Required fields are marked *