Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only select one row at a time using jquery

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)?

like image 579
themerlinproject Avatar asked Nov 16 '11 22:11

themerlinproject


2 Answers

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.

like image 151
James Allardice Avatar answered Sep 26 '22 13:09

James Allardice


Use this script at end of your html,meant after </body> tag

<script>
 $("tr").hover(function() 
 {
   $(this).addClass("hover"); 
 }, function()
    {
    $(this).removeClass("hover");
    });
$('tr').click(function(event) {
        $('tr').not(this).removeClass('click');
        $(this).toggleClass('click'); 
    });
</script>


This is css that highlight your row:

    .click{
background:#FF9900;
color: white
}

.hover{
background:blue;
color: white
}

here is the link of working example

Working example

Hope this will help
like image 30
Rameshwar Chaturvedi Avatar answered Sep 22 '22 13:09

Rameshwar Chaturvedi