Reputation: 6264
i have following code to show div on page
<div id="all_users">
<div id=user11 userid=11 class=innertxt><img src=images/images.jpg width=50 height=50>
<strong>User11</strong>
<ul> <li>Email: [email protected]</li>
<li> <input type=checkbox id=select11 value=11 class=selectit /></li>
</ul> </div>
<div class="float_break"></div>
</div>
following code work fine and print "test in log window"
$('#all_users .selectit').click(function() {
console.log("test");
});
but when i add div from following code, it didn't show "test in log windows" mean this click event is not activated
var new_data_var = $('<div class="innertxt" userid="1" id="user1"> <img height="50" width="50" src="images/images.jpg"><strong>Test User 01</strong><ul><li>User ID: 1</li> <li>Email: [email protected]</li><li style="padding-top: 5px;"><input type="checkbox" class="selectit" value="1" id="select1"><label for="select1"> Select it.</label></li></ul></div>');
$('#all_users').append(new_data_var);
event is not called ?
Thanks
Upvotes: 0
Views: 3116
Reputation: 8011
You have to use live():
Binds a handler to an event (like click) for all current - and future - matched element.
For example:
$('#all_users .selectit').live('click', function() {
console.log("test");
});
Right now you are using click() which delegates to bind().
The main difference is that live, contrary to bind, works also with newly created DOM elements.
Upvotes: 2
Reputation: 5695
you should check that your binding the click after the dom element is created or replace bind
with live
which behave similarly but also affect not yet existing element.
ps: your html attribute values should be quoted. eg, type=checkbox
=> type="checkbox"
Upvotes: 1
Reputation: 37516
If you are setting the click
event before you create the input box, the click event will not be registered - it will only register the click event for DOM elements that exist at that time. You can either create the input box before calling $('#all_users .selectit').click(function() { ...
or by using the live() function as others have suggested, which will attach the click event for all elements that match the selector and all elements in the future.
Upvotes: 0
Reputation: 382841
live() method must do the trick there:
$('#all_users .selectit').live('click', function() {
console.log("test");
});
Description: Attach a handler to the event for all elements which match the current selector, now or in the future.
Source: http://api.jquery.com/live/
Upvotes: 1