Reputation: 1085
I have a table that contains rows with different class names. Some of these rows have the same class names. I am trying to select the next table row (using jQuery) that contains a particular class. Basically, I am attempting to create a feature where a user can select the next row in a table by using the arrow keys. Here is the code I am using:
if (e.keyCode == 40)
{
$('tr.background_color_grey').next("tr").addClass("background_color_grey");
$('tr.background_color_grey:first').removeClass("background_color_grey");
return false;
}
The problem is that I need to skip over some rows (they act as headers for different categories in the table). So, how can I select the next row in the table, provided that it has a particular class? All of the rows that I would like to be selected have the class "can_be_selected". Thanks for any help!
Upvotes: 0
Views: 3503
Reputation: 208032
How about something like this jsFiddle example?
The example has a table with one column and 10 rows. Cells are all <td>
elements where selected cells have the class can_be_selected
. By using your up and down arrow keys you can highlight the cells with the class can_be_selected
only with the other cells being ignored. Note that in the example, I gave the cells that have the class can_be_selected
a green border to make them distinct, but you can easily remove this.
This is a second jsFiddle example using the same code where table rows have been substituted for table cells.
jQuery (for the first jsFiddle example):
var index = -1;
//38 up, 40down
$(document).keydown(function(e) {
if (e.keyCode === 40) {
index = (index + 1 >= $('td.can_be_selected').length) ? $('td.can_be_selected').length - 1 : index + 1;
$('td.can_be_selected').removeClass('background_color_grey');
$('td.can_be_selected:eq(' + index + ')').addClass('background_color_grey');
return false;
}
if (e.keyCode === 38) {
index = (index == 0) ? 0 : index - 1;
$('td.can_be_selected').removeClass('background_color_grey');
$('td.can_be_selected:eq(' + index + ')').addClass('background_color_grey');
return false;
}
});
Upvotes: 1
Reputation: 145478
One option is using nextUntil
method to skip all 'useless' rows:
$("tr").eq($("tr.selected").nextUntil(".can_be_selected").next().index());
DEMO: http://jsfiddle.net/y8Dqq/
Upvotes: 0