superUntitled
superUntitled

Reputation: 22527

bind custom function to dynamically loaded elements

I have written a simple function:

function inputChanged()
  {
    $('input').change(function(){
      $(this).addClass('changed');
    });
  }

I am adding forms dynamically to a div and would like to bind the function to the added forms, I have tried like this:

// add a new form on click
$('.addForm').live({
    click: function(e) {
        e.preventDefault();
        $("<div>").load("directory/theform.html", function() {
            $("#theForms").prepend($(this).html());
                    // i am calling the function here...
            $("#theForms form:last").validate().inputChange();
        });
    }
});

This is not working for me... How can I bind this function to the dynamically loaded forms?

Upvotes: 1

Views: 1138

Answers (4)

James Johnson
James Johnson

Reputation: 46057

You can create custom jQuery functions like this:

jQuery.fn.inputChange = function() {         
    $(this).change(function(){
        $(this).addClass("changed");
    });         
    return this; 
} 

And then you can use it like this:

$("#theForms form:last").inputChange(); 

Upvotes: 2

rossipedia
rossipedia

Reputation: 59397

Change your first function to:

function inputChanged()
{
  $('input').live('change', function(){
    $(this).addClass('changed');
  });
}

Or better yet, use jQuery 1.7's new on() method insteda.

Upvotes: 1

yunzen
yunzen

Reputation: 33439

Which version of jquery do you have?

You use events-maps which was added in 1.4.3. See here http://api.jquery.com/live/

Upvotes: 0

rafael.js
rafael.js

Reputation: 600

$(".addForm").live("click",function(e){

});

Upvotes: 0

Related Questions