Reputation: 5911
I have a table. When a row is clicked on, it is given .active
and the row is highlighted. I need to work on other ways to change the selected row other than clicking on it. For my example, I've chosen a next button.
I can do the logic behind what happens when it gets to the end of the table or anything else like that.
I just need help figuring out how to get the index of the TR with class active so that I can increase the index, which then I can give the next row the active class... That's all I need to do... how to get that row index.
This is some of the stuff I've tried that doesn't work...
alert( $('table tr .active').index() );
var row = $('table tr.active').first();
alert(row.index() );
alert($("table").index( $('table tr .active') ));
This is what I'm using as a reference (https://stackoverflow.com/a/469910/623952)
var index = $("table tr").index($(this));
but I can't get the selectors right...
Solution.....
it would have never worked... I wrote bad code:
$(this).children("tr").addClass("active");
(this = clicked on tr in the click function)
But new code: http://jsfiddle.net/dHxKW
$("#table_one").on("click", "tr", function () {
$(".active").removeClass("active");
$(this).children("td").addClass("active");
// removed line: $(this).children("tr").addClass("active");
$(this).addClass("active");
});
$('#btn_next').on('click', function ()
{
// right here **********
var n = $('tr.active').next();
$(".active").removeClass("active");
n.children("td").addClass("active");
n.addClass("active");
});
** Just as a note, I am adding the class to both the tr and td's... I'm not sure if this is the best way but tr doesn't have background properties, so I just added it to both. I think this might be the reason for my confusion....
Upvotes: 3
Views: 5236
Reputation: 76
$('table tr .active').removeClass('active').parent().next().children('td').addClass('active');
this should do it
Upvotes: 1
Reputation: 207900
$('td.active').parent().index('tr')
will get you the index.
BTW, the link in your click function $(this).children("tr").addClass("active");
would seem to do nothing as it searches for a child row of a row.
Upvotes: 2
Reputation: 2875
var counter = 0;
var index = -1
$('table tr').each(function(){
if( ! $(this).hasClass('active')) {
counter++;
}
else index = counter;
})
Upvotes: 1
Reputation: 10658
The issue is that the "active" class is not being added to the "tr" elements.
In this line you are looking for tr
children of this
, but this
is a tr
, thus no children get selected: $(this).children("tr").addClass("active");
Instead try $(this).addClass("active");
Upvotes: 1