Jake
Jake

Reputation: 16837

Problem with jquery button click

I am facing a problem in the jquery click event.

My web page involves creating a button through javascript and assigning a class to the button ( call it A ). Now I want to detect the click of that button and I have written the following code for it :

 $(".A").click( function () {

    // do something

 });

To my surprise, this click event never gets called.

But when I make the button statically on the webpage ( during design time ), the same code works.

Is there a different approach to bind a button click with jquery in case a button is created dynamically?

Upvotes: 1

Views: 358

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

Your event handler fires at page load, before your button exists.

Either reset the event handler after you create the button, or use .live for late-binding:

$(".A").live('click', function () {
   // do something
});

Now the handler will apply to .A even created in the future.

Upvotes: 0

DavidGouge
DavidGouge

Reputation: 4623

Have a look at the live() jquery method to automatically wire up events to new elements. Or, as you create the new button, attach the new click event.

var newbutton = $('<input type="button" value="click me"/>');
somediv.append(newbutton);
newbutton.click(yourhandler);

Upvotes: 0

Felix Geenen
Felix Geenen

Reputation: 2707

you have to use the live-function of jquery! In difference to the click-function, it watches for dom manipulations. as you can imagine its slightly slower than the .click().

$('.clickme').live('click', function() {
  // Live handler called.
});

Felix

Upvotes: -1

Dogbert
Dogbert

Reputation: 222118

You need to use $.live

$(".A").live('click', function () {

   // do something

});

Upvotes: 3

Related Questions