I’ve added tr and td tags to a table using append but I jQuery doesn’t seem to know the dom objects are there (I thought that’s what append/prepend did?). When I run the script the table row is added and the user can see it but jQuery isn’t catching the click handler on the hyperlink or anything else. I’ve done the same thing on a different page that works great. I’ve included that as well. If someone could please tell me where my train of thought got derailed, I’d be much obliged. Also if I’m going about this the wrong way please let me know so I can improve.
broken code:
$("#addAdmin").click(function(){
$("#chosenAdmins").append('<tr id = "admin' + $("#admins").val() + '"><td align="left">' + $("#admins option:selected").text() + ' </td><td align="right"><a href="#" class = "removeAdmin" id = "ra" style = "font-size: 10px;">Remove</a></td><tr>');
});
$(".removeAdmin").click(function(e){
e.preventDefault();
alert('clicked');
alert(this.attr(id));
});
<select id = "admins">
<option value = "1">bob smith</option>
</select>
<input type = "button" id = "addAdmin"/>
<table id = "chosenAdmins" align="center" width="0%"> </table>
The similar code that works on a different page is:
$(document).ready(function() {
var leftData = '<div id = "l1">left Stuff</div>';
var leftData = leftData + '<div id = "l2">left Stuff</div>';
var rightData = '<div id = "r1">right Stuff</div>';
var rightData = rightData + '<div id = "r2">right Stuff</div>';
$("#selector").prepend("<div id = 'leftSelect' style = 'float:left'>"+leftData+"</div><div id = 'rightSelect' style = 'float:left'>"+rightData+"</div>");
$("#l1").click(function(){
$(this).hide("fast", function(){
$(this).prependTo('#rightSelect');
$(this).show("fast");
});
});
});
<div id = "selector"> </div>
You are defining your event handler (
$('.removeAdmin').click()) before there are any.removeAdminelements on the page.What you need to do is delegate your events. Assuming you’re using the latest jQuery:
This way, the event handler is attached to an element that exists, namely, the
chosenAdminstable.NOTE It is not recommended to use
.live, as this attaches events to the document, and other code may inadvertantly remove these events. If you are using jQuery < 1.7, usedelegate: