DavidTonarini
DavidTonarini

Reputation: 951

Attaching handler from a jquery element to an other

I have a jquery handler attached to forms in my page. I then dynamically load some components, that might include a form, which is supposed to get the same jquery handler.

I know about this, and that I am supposed to use .live() or .on() in order to attach the handler to this dynamically loaded component, and I´ve successfully applied this technique elsewhere.

In this case, however, I find difficult to use .on(), since I don´t want to write again the code for the new form. Is it possible to tell an element to apply the same handler as an other?

So, this is my code structure

$(".myForm").submit(
            function() { alert("do stuff");}
      );

$(".loadPage").click(
       function() {
             $.post( "my_url.php",
        "my_var = " + my_var, 
                 function( data) {
                                //data may contain a form, that is supposed to behave just as myForm
               $("#container").html( data );

                           //now I shoudl be able to apply the handler, but I´m not sure how
                           $("#container .myForm").submit( sameHandler ); 
                      }
               }
      );

So, what I don´t know and I´m not able to figure out is how to define that "sameHandler". By the way, the dynamically loaded form does have the "myForm" class, if that helps, but I don´t know if there is any way to "refresh" jQuery instructions on dynamically loaded elements.

Upvotes: 0

Views: 50

Answers (2)

mmm
mmm

Reputation: 2297

You can assign a function to a variable and use the variable name to call the function later. Just make sure that it's in a scope that's accessible from your $.post(). Also, using .on() is almost always just as fast or faster than .submit() or .click() etc...

var submitHandler = function() {
  alert("do stuff");
};

$(".myForm").on('submit', submitHandler);

$(".loadPage").click(function () {
  $.post("my_url.php", "my_var = " + my_var, function (data) {
    $("#container").html(data);
    $("#container .myForm").on('submit', submitHandler);
  });
});

Upvotes: 1

lucasjackson
lucasjackson

Reputation: 1525

You can add the submit event to the document and couple it with a selector

$(document).on("submit", ".myForm", function(){alert("do stuff");});

You can also declare a function variable that you can use in multiple places

var sameHandler = function() {
    alert("do stuff");
};

$(".myForm").submit(sameHandler);
$("#container .myForm").submit(sameHandler);

Upvotes: 1

Related Questions