-1

how to validate a form which is loaded via AJAX on page. i'm using jquery validate.js. plugin. i call the validate function after the form is loaded via ajax, but it doesn't work.

jquery code :

  $(document.body).on('click', '.submitBtn', function(){
    var id=$(this).attr('id');
   $("#form"+id).validate({
     submitHandler: function() {

        // do anything

     }
   });
});

Any help will be highly appreciated.

Chetan Gawai
  • 2,361
  • 1
  • 25
  • 36
shilpi Singh
  • 402
  • 1
  • 5
  • 15

2 Answers2

0

If I assume you have a main page and the ajax form in ajax page, looks like you are keeping the code for that form validation in the main page statically. Even before the ajax happens.

So when the main page loads, the validation code runs but it does not find the "#form"+id(coz it's not loaded yet). Hence event bindings by the plugin fail.

What you can do is to send in the validation script along with your ajax response so that the validation code runs ONLY AFTER you have loaded the form and the events are properly bound.

OLD AJAX FILE

//contains only the form

NEW AJAX FILE

//contains the form 
//then contains the validation code.

NOTE - There are other ways to do it. Like using jQuery's live method. Quick Googling will give you quite a few results.

Praveen Puglia
  • 5,577
  • 5
  • 34
  • 68
  • 1
    If you look at his code carefully, you will find he's well and truly using delegate(the event originated from .submitBtn is delegated by document.body). So its binding is OK. Look at my answer, – wander Apr 25 '14 at 08:43
  • what if the `id` is a string and it builds a string like "#formTHESTRING" the selector is fine. – Praveen Puglia Apr 25 '14 at 08:55
  • "#formTHESTRING" means an element with an id of "ormTHESTRING". Clearly it's a wrong selector. – wander Apr 25 '14 at 08:57
  • @wander - http://jsfiddle.net/6Pup5/ . You might be thinking `form` is an element selector but in this case, it's just a plain simple string. much like prefix for the `id` var indicating the `id` is for a form element. – Praveen Puglia Apr 25 '14 at 09:17
  • @ShilpiSingh - Glad! Accept the answer when you can! :) – Praveen Puglia Apr 25 '14 at 09:18
0

It's a simple syntax error, change "#form"+id to "form#"+id Here's the jsfiddle.

$(document.body).on("click", "form", function () {
    var id = $(this).attr('id');
    $("form#" + id).validate({
        submitHandler: function () {
            alert("submit");
        }
    });
});

I wonder why do you use this ugly way of selecting element. If the form does not have an id attribute, the selection will fail. I think this is better

wander
  • 937
  • 1
  • 7
  • 15