2

I have a code the change the html of a div to make a button. When I make a click handler for the dynamic button, nothing happens

$('#signinup').html("<button id=\"login_submit\">Sign In</button>");

And the handler:

$('#login_submit').click(function() {
   alert("Works!");
});
2
  • When does the click handler code run in conjunction with the HTML generation? Also, have you tried the bind or live event handler methods? Commented Jun 9, 2010 at 20:20
  • Are you sure, you add your handler after the button is created? Commented Jun 9, 2010 at 20:20

2 Answers 2

9

See the working demo :)

Use the live() method:

$('#login_submit').live('click', function() {
   alert("Works!");
});

The live() method attach a handler to the event for all elements which match the current selector, now or in the future.

Sign up to request clarification or add additional context in comments.

2 Comments

@joshperry: Thanks for notifying that, actually I posted a wrong working link, updated now. Thanks
"live" function is deprecated if working with new versions of jQuery just change the "live" function for the "on" function api.jquery.com/on
3

.live doesn't work always. Many a times it does, but recently I crashed at a situation wherein I am updating/loading the buttons dynamically which performs some action. Just like you see the Confirm friend request button in facebook friend requests popup flyout.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.