Reputation: 243
Yesterday i questioned how to add a new table row but change the css of the duplicated row. I got an answer to that question!(link) however a new issue has arised.
i have a table as follow:
<table class="test">
<thead>
<tr>
<td><b>header 1</b></td>
<td><b>header 2</b></td>
<td><b>header 3</b></td>
<td><b>header 4</b></td>
</tr>
</thead>
<tbody>
<tr class="1">
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td class="remove"></td>
</tr>
<tr class="2">
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td class="remove"></td>
</tr>
<tr class="new">
<td>data 1</td>
<td>data 2</td>
<td>data 3</td>
<td class="new"></td>
</tr>
</tbody>
<table>
Jquery code:
$("table.test tr.new:last td.new").click(function(){
var x = $('table.test tr.new:last').clone(true);
$(this).removeClass('new').addClass('remove').off('click');
x.insertAfter('table.test tr.new:last');
});
$("table.test tr td.remove").click(function(){
$(this).closest("tr").fadeOut('slow');
});
When i click the td.new cell i want to add a row. This is working. Also the class is changed in a td.remove cell. However the click events do not work correct. The remove cell should allways remove a row. I have figured out that I have to use .off() and .on functions but I can't seem to understand the logic behind this functions. The following image is what i am aiming for: postimage
Jsfiddle example of what i have now can be found here
Upvotes: 0
Views: 1957
Reputation: 55750
You seem to adding the row Dynamically right.. So you need to delegate the event..
Instead of
$("table.test tr td.remove").click(function(){
try
$("table.test").on('click','td.remove', function(){
UPDATE
You can handle both the case in a single handler itself.. Made a few modifications in your code..
$("table.test").on('click', 'td.remove,td.new', function() {
var $this = $(this);
if ($this.hasClass('new')) {
var x = $('table.test tr.new').clone();
$this.removeClass('new').addClass('remove');
$this.closest('tr').removeClass('new');
x.insertAfter('table.test tr:last');
}
else if ($this.hasClass('remove')) {
$(this).closest("tr").fadeOut('slow');
}
});
Upvotes: 1
Reputation: 2396
You should use jquery .live(), I know it's going to be deprecated, but it would be a simple starting point for you. http://api.jquery.com/live/
It will hook on the remove elements that will be added to the DOM in the future. SO you would not need to handle any reinitilizations and stuff.
EDIT:
So back again to .live(), since it is deprecated you should achieve that by:
$(document).on(events, selector, data, handler);
In your case: $(document).on('click', '.remove', function(){ //whatever it is you want to do });
Upvotes: 0