themerlinproject themerlinproject - 9 days ago 5
jQuery Question

only select one row at a time using jquery

So I am using

mouseover()
,
mouseout()
and
click()
to highlight rows on mouseover and add a highlight class on click:

//Mouseover any row by adding class=mouseRow
$(".mouseRow tr").mouseover(function() {
$(this).addClass("ui-state-active");
});
$(".mouseRow tr").mouseout(function() {
$(this).removeClass("ui-state-active");
});
$('.mouseRow tr').click(function(event) {
$(this).toggleClass('selectRow');
});


The above code will allow a user to 'highlight' (i.e add class
selectRow
) to as many rows as they want. What is the best way, using jQuery, to limit the number of rows they can select to just one (so that if they click one row, then click another it will remove the '
selectRow
' class from the previously selected row)?

Thanks

Answer

You could remove the selectRow class from all of the tr elements except the clicked one whenever you click on one, and then toggle it on the clicked one:

$('.mouseRow tr').click(function(event) {
    $('.mouseRow tr').not(this).removeClass('selectRow');
    $(this).toggleClass('selectRow'); 
});

Here's a working example.

Comments