How to highlight color of selected table row using name attribute in jquery

I want to highlight the color of only the selected row in the table. I make the background colors of all rows alternate using an even technique. But now, when I click on some line, all the alternating background behavior is broken. Here is the code:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="java.util.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="jkl.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    $(document).ready(function() {
        $('tr[name=t1]').each(function(a, b) {
            $(b).click(function() {
                $('tr[name=t1]').css('background', '#D8D8D8');
                $(this).css('background', '#F2F5A9');
            });
        });
    });
</script>
<script>
    function radioselect(id) {
        document.getElementById("ra" + id).checked = true;
    }
</script>
</head>
<body>
    <table border="1">
        <%
            if (session.getAttribute("al") != null) {
                ArrayList<Pojo> al = (ArrayList<Pojo>) session
                        .getAttribute("al");
                if (al.size() > 0) {
                    for (Pojo p : al) {
                        if (al.indexOf(p) % 2 == 0) {
        %>
        <tr name="t1" id="<%=al.indexOf(p)%>" style="background: #81DAF5;"
            onclick="radioselect(this.id);">
            <%
                } else {
            %>

        <tr name="t1" id="<%=al.indexOf(p)%>" style="background: #D8D8D8;"
            onclick="radioselect(this.id);">
            <%
                }
            %>
            <td><input type="radio" id="ra<%=al.indexOf(p)%>" name="r" /></td>
            <td><%=p.getUid()%></td>
            <td><%=p.getUname()%></td>
            <td><%=p.getUpassword()%></td>
            <td><%=p.getUtype()%></td>
        </tr>
        <%
            }
                }
            }
        %>
    </table>
</body>
</html>

      

output: when i don't click any line

enter image description here

output after clicking

enter image description here

how can i maintain alternate line coloring by highlighting the highlighted line.

+3


source to share


2 answers


Try the following:

Style

tr:nth-child(odd){ background-color: #ddf7ef;}
body table tr.selectedRow{background-color: #fff2e1;}

      



Scripts

$("table tr").click(function(){
    $("table tr").removeClass('selectedRow');
    $(this).addClass('selectedRow');
});

      

Take a look: JSFiddle

+2


source


use active



table tr:active {
    background-color: yellow;
}

      

0


source







All Articles