Check if td is next to last of tr with jQuery
I select a textbox in a gridview row. I know that a gridview is a html-table. How can I find out whether the td where the textbox is in is the next to last td in the tr of the table with jQuery?
<asp:GridView runat="server">
<Columns>
<asp:TemplateField HeaderText="Standardpreis">
<ItemTemplate>
<asp:TextBox runat="server" ID="valueTxt"></asp:TextBox>
</Ite开发者_开发问答mTemplate>
</asp:TemplateField>
</Columns>
Something like this in the event for the child element
var $that = $(this),
$td = $that.closest('td'),
trChildrenCount = $td.parent().children().length,
tdBeforeLast = trChildrenCount - 1,
tdIndex = $td.index() + 1; // get 1-based index
if (tdBeforeLast === tdIndex) {
console.log('next to last td');
// do stuff...
}
example jsfiddle
<script type="text/javascript">
$(function () {
var $td = $("#second"); // swap this to #first to test
if ($td.index() === $td.siblings().length - 1) {
console.log("2nd last");
} else {
console.log("not 2nd last");
}
});
</script>
<table>
<tr>
<td id="first">first</td>
<td id="second">second</td>
<td id="third">third</td>
</tr>
</table>
In your example, if you're looking for a specific textbox, it's probably easiest to put a CssClass on the textbox, and look for its parent. In that case, the selector for the $td would look like the following:
var $td = $(".someTextBoxClass").closest("td");
You could do something like this:
var td = $(selector); // The 'td' you want
var tdLength = td.closest('tr').children('td').length; // Get the number of tds in the tr
if(td.index()+1 == tdLength-1){ // Is it second to last (.index() is zero-based)
}
Demo: http://jsfiddle.net/Y5s2p/
JavaScript
$('#test td').click(function(){
var lng = $('td', $(this).parent().parent()).size();
var myIndex = $('td', $(this).parent().parent()).index(this);
if(lng-1 == myIndex+1)
console.log('next to the last');
});
HTML
<table id="test">
<tbody><tr><td>First Row</td></tr>
<tr><td>Middle Row</td></tr>
<tr><td>Last Row</td></tr>
</tbody></table>
精彩评论