Reputation: 12816
This is no doubt simple, but my lack of knowledge about jquery makes it complex for me. Basically I have this code:
$(document).ready(
function() {
$( "#remove")
.click(function() {
alert("I have been clicked!");
$(this).parent().parent().remove();
});
});
I add a button to a table meant to remove it's row (see above code). The button is as follows:
<td ><button id='remove' type='button'>Remove</button></td>
However, it does nothing when clicked. I think this may have something to do with the fact the button is created after the document is loaded... no idea what to do about it, though.
Upvotes: 1
Views: 1349
Reputation: 87073
$( "td").on('click', '#remove', function() {
alert("I have been clicked!");
$(this).parent().parent().remove();
});
As you're trying to add button dynamically so you need delegate event handler (aka, live event).
An in jQuery > 1.7 delegate event declare as
$(container).on(eventName, target, handlerFunction);
For more detail see .on()
You have another option called .delegate()
and its declaration process is:
$(container).delegate(target, eventName, handlerFunction);
So for your case it will look like:
$('td').delegate('#remove', 'click', function() {
alert("I have been clicked!");
$(this).parent().parent().remove();
});
here container
means the holder of #remove
button which belong to DOM at page load. From you post it seem td
, you may have something else (any valid jQuery selectors)
container
for #remove
then use $(document)
or $('body')
instead of $('td')
.Upvotes: 5