Andy Kaufman Andy Kaufman - 1 year ago 55
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){

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)

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.


Answer Source

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:

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

or with pure js:

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download