dangerisgo dangerisgo - 1 year ago 73
ASP.NET (C#) Question

asp mvc change row color in table upon click, one at a time

I have created a table in ASP MVC and populate it with data from a database. I have alternating row colors using the following code:

<% if (count % 2 == 0) { %>
<tr class="offeven" onclick="this.className='onclick'" onmouseover="this.className='on'" onmouseout="this.className='offeven'">
<% } %>
<% else { %>
<tr class="offodd" onclick="this.className='onclick'" onmouseover="this.className='on'" onmouseout="this.className='offodd'">
<% } count++; %>

each class has a different background color. So what I want is this to happen. When a user goes to the page, they will see the table w/ alternating row colors and when a mouse hovers over every row, that row in question changes color. When they select a row, the row changes to a different color and stays, even after the mouse has gone beyond the scope of the row (so onmouseout doesn't function). Now I wrote a very Javascript functions for my old website which used gridviews and I don't think that they will work in this case (at least without some modifications). How would I go about accessing a table's rows through Javascript and doing what I need to get done?

Edit: I added the :hover into the CSS and that works (in FF, not in IE6) in the sense that the clicked row doesn't lose its background color after the mouse leaves the scope of that row. But the last hurdle is that I need any row to change to its original background color when a new row is clicked, because at the moment, each row highlights, but doesnt de-highlight.

Answer Source

You can do it using some jquery

$(”table tr:even”).addClass(”offeven″);

Add some CSS deceleration for instead of using onmouseover

.offeven:hover, .offodd:hover

Maybe a better cross-browser solution is mentioned in this post:

jQuery Alternating Gray Rows in a Table, and Highlight Table Row Mouseover Example