Reputation: 9146
I have a 3 tables that every row have 2 \ 4 \ 6 columns , and the last column contains a edit button.
When I press the edit button, I want all the other td
's will turn into a textboxes.
The script:
$(".icon-pencil").click(function () {
var row = $(this).parent('td').parent('tr');
row.find('td').each(function () {
$(this).html("hi");
});
});
a row example:
<tr>
<td>1</td>
<td>
<img src="img/couponimg.png" alt="" />
</td>
<td>1</td>
<td>A coupon for ..</td>
<td><i class="icon-pencil"></i>
</td>
<td><i class="icon-remove"></i>
</td>
</tr>
It works as I want, but it applies the change to all the <td>
, and I don't want to change the last one.
How to prevent to affect to the last one?
Upvotes: 1
Views: 1104
Reputation: 148524
Try this and use :not(:nth-last-child(-n+2))
which will EXCLUDE the last 2 columns.
$(".icon-pencil").click(function() {
var row = $(this).closest('tr');
row.find('td:not(:nth-last-child(-n+2))').each(function() {
$(this).html("hi");
});
});
example :
http://jsbin.com/oyUvAhi/2/edit
2 changes :
closest
instead of .parent('td').parent('tr')
TR
- select only the relevant TD's for change.please read @François Wahl comment - which helps shorten the code :
row.find('td:not(:nth-last-child(-n+2))').html("hi");
Upvotes: 0
Reputation: 27823
Since your HTML is well formed, in this particular situation, the :last
CSS selector works nicely, so you can use that. I will give you a more general solution, when the element is not the last node in the parent, or perhaps not even the last node of its type in the parent (:last-of-type
).
jQuery objects are collections of elements. The CSS selector usually used to create such a collection is matched on the DOM, but once you have a jQuery object you can manipulate it any way you want. If you want to eliminate the last element, you can do something like this:
var myJQueryObject = $('mySelector');
Array.prototype.splice.call(myJQueryObject, myJQueryObject.length-2, 2); // removed the last two elements
This relies on the fact that jQuery objects are Array-like objects (have a length property and numeric-like keys) and Array.prototype.*
methods work on Array-like objects.
Upvotes: 0
Reputation: 338178
I recommend event delegation.
$(document).on('click', '.icon-pencil', function () {
$(this).closest('tr').find('td:not(:last)').html("hi");
});
Also,
$('something').each(function() {
$(this).html("hi");
});
is equivalent to
$('something').html("hi");
Upvotes: 3
Reputation: 3965
Try this:
row.find('td').each(function() {
$(this).not('td:last-child').html("hi");
});
Upvotes: 1