Andy Kaufman Andy Kaufman - 5 months ago 14
HTML Question

Highlight One Row of a Table with Javascript

Hello good people of StackOverflow,

Apologies in advance for how monumentally stupid I am being, but I need your help.

I have a table which is generated by an SQL query and the user needs to be able to select one row, which passes a value into a hidden text box. This bit I have managed to do OK, but I need to show which row they have selected, and if they change their mind and then select a different row, only the new row is highlighted.

I know this should be pretty basic, but I can't work out the logic. So far I have this:

function getOLBC(olbc){

document.getElementById("ANSWER.TTQ.MENSYS.1.").value=olbc;
var rows = document.getElementById("results").getElementsByTagName("tr").length;
for (var i =0; i < rows; i++)
{
var answer = document.getElementById("ANSWER.TTQ.MENSYS.1.").value
if (answer = olbc)
{
document.getElementById(olbc).style.background="red";
document.getElementById(olbc).style.color="white";
}
else
{
document.getElementById(olbc).style.background="white";
}
}
}


The HTML looks like this:

<tr class="unselected" id="AL-AAA98"onclick="getOLBC('AL-AAA98')"><td class="OLBC">AL-AAA98</td><td>AAAL</td><td>Grade A in Economics<br />Grade A in Mathematics<br />Grade A in Business Studies</td><td></td></tr>
<tr class="unselected" id="AL-AAA77"onclick="getOLBC('AL-AAA77')"><td class="OLBC">AL-AAA77</td><td>AAAL</td><td>Grade A in Economics<br />Grade A in Mathematics<br />Grade A in Spanish</td><td></td></tr>
<tr class="unselected" id="AL-AAA42"onclick="getOLBC('AL-AAA42')"><td class="OLBC">AL-AAA42</td><td>A*AAL</td><td>Grade A in Mathematics<br />Grade A in Human Biology<br />Grade A in Physics</td><td></td></tr>


Can anyone help? Apologies for the n00bish-ness of this question.

Thanks!

Answer

I think this is what you are looking for... I removed the onclick dom element (better to separate the js from the dom).

with jquery: http://jsfiddle.net/cr1urhv6/

$("#myTable tr").click(function(e) {
  $("#myTable tr").removeClass("highlight");
  $(this).addClass("highlight");
});

or with pure js: http://jsfiddle.net/cr1urhv6/1/

var rows = document.querySelectorAll("#myTable tr");
for (var i = 0; i < rows.length; i++) {
    rows[i].addEventListener('click', function() {
        [].forEach.call(rows, function(el) {
            el.classList.remove("highlight");
            });
        this.className += ' highlight';
    }, false);
}

This is removing any current highlighting... and then adding the highlight class to the TR we clicked within.