简体   繁体   中英

Highlighting and Un-Highlight a table row on click from row to row

I've been at this problem for awhile with no luck.

Please note. No jquery =/

The JS code I have is as following

function highlight(){
 var table = document.getElementById('dataTable');
 for (var i=0;i < table.rows.length;i++){
  table.rows[i].onclick= function () {
   if(!this.hilite){
    this.origColor=this.style.backgroundColor;
    this.style.backgroundColor='#BCD4EC';
    this.hilite = true;
   }
   else{
    this.style.backgroundColor=this.origColor;
    this.hilite = false;
   }
    }
 }
}

The HTML is as following

<table id="dataTable">
  <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
  <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
  <tr onclick="highlight()"><td>Data1</td><td>Data2</td></tr>
</table>

Currently when I click it changes color, however when I click on the second row the first row still remains highlighted. Could you please assist me in accomplishing this task with no jquery?

Thank you.

I've created a working example of the following on JSFiddle

Javascript:

function toggleClass(el, className) {
    if (el.className.indexOf(className) >= 0) {
        el.className = el.className.replace(className,"");
    }
    else {
        el.className  += className;
    }
}

HTML:

<table class="gridview">
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
   <tr onclick="toggleClass(this,'selected');"><td></td><td></td></tr>
</table>

CSS:

.gridview .selected, .gridview tbody .selected {
    background-color: #6ccbfb;
    color: #fff;
}

I was in the same problem recently and just solved it using pure JS Here is my version of it https://jsfiddle.net/armaandhir/Lgt1j68s/

function highlight_row() {
    var table = document.getElementById('display-table');
    var cells = table.getElementsByTagName('td');

    for (var i = 0; i < cells.length; i++) {
        // Take each cell
        var cell = cells[i];
        // do something on onclick event for cell
        cell.onclick = function () {
            // Get the row id where the cell exists
            var rowId = this.parentNode.rowIndex;

            var rowsNotSelected = table.getElementsByTagName('tr');
            for (var row = 0; row < rowsNotSelected.length; row++) {
                rowsNotSelected[row].style.backgroundColor = "";
                rowsNotSelected[row].classList.remove('selected');
            }
            var rowSelected = table.getElementsByTagName('tr')[rowId];
            rowSelected.style.backgroundColor = "yellow";
            rowSelected.className += " selected";

            msg = 'The ID of the company is: ';
            msg += rowSelected.cells[0].innerHTML;
            msg += '\nThe cell value is: ' + this.innerHTML;
            alert(msg);
        }
    }

} //end of function

window.onload = highlight_row;

you need to un-highlight the other rows, because now you are just changing the clicked one.

function highlight(){
 var table = document.getElementById('dataTable');
 for (var i=0;i < table.rows.length;i++){
  table.rows[i].onclick= function () {
   if(!this.hilite){
    unhighlight();
    this.origColor=this.style.backgroundColor;
    this.style.backgroundColor='#BCD4EC';
    this.hilite = true;
   }
   else{
    this.style.backgroundColor=this.origColor;
    this.hilite = false;
   }
    }
 }
}

function unhighlight(){
 var table = document.getElementById('dataTable');
 for (var i=0;i < table.rows.length;i++){
   var row = table.rows[i];
   row.style.backgroundColor=this.origColor;
   row.hilite = false;
 }
}

not able to unhighlight rows when deselected

 <script type="text/javascript">

  function highlight(){
  var hilite;  
 var table = document.getElementById('dataTable');
 for (var i=0;i < table.rows.length;i++){
  table.rows[i].onclick= function () {
   if(!this.hilite){
    unhighlight();
    this.origColor=this.style.backgroundColor;
    this.style.backgroundColor='#fdee9a';
    this.hilite = true;
   }
   else{
    this.style.backgroundColor=this.origColor;
    this.hilite = false;
   }
    }
 }
}

function unhighlight(){
  var hilite;
 var table = document.getElementById('dataTable');
 for (var i=0;i < table.rows.length;i++){
   var row = table.rows[i];
   row.style.backgroundColor=this.origColor;
   row.hilite = false;
 }
}

  </script>

You can use Azle if you provide a class name and id to each row :

HTML

<table class="dataTable">
  <tr class='dataTable_row' id='row_a'><td>Data1</td><td>Data2</td></tr>
  <tr class='dataTable_row' id='row_b'><td>Data1</td><td>Data2</td></tr>
  <tr class='dataTable_row' id='row_c'><td>Data1</td><td>Data2</td></tr>
</table>

AZLE

create_azle(function() {
    az.highlight_row_on_click('dataTable', 1, 'limegreen')
})

Result :

在此输入图像描述

Here is the FIDDLE

If you're creating larger tables , you'll need to be sure the table has rendered prior to attaching events. You can use Azle's call_once_satisfied function:

az.call_once_satisfied({
     "condition" : "az.get_row_count('my_table', 1) > 0",
     "function" : "az.highlight_row_on_click('my_table', 1, 'limegreen')"
 })

Here's an example, where the table is created from an API call, and the highlight event attached once the table has rendered:

在此输入图像描述

Here is the FIDDLE for this one.

This demo table row selection has the functionality:

  • Selects a clicked row, and unselects any previously selected row
  • If already selected row is clicked on, it is unselected

NOTE: This is based upon the answer posted by @Richard YS

HTML:

 <table>
    <thead>
      <tr>
        <th>Name</th>
        <th>Country</th>
      </tr>
    </thead>
    <tbody>
      <tr onclick="selectRow(this,'selected');">
        <td>Maria Anders</td>
        <td>Germany</td>
      </tr>
      <tr onclick="selectRow(this,'selected');">
        <td>Francisco Chang</td>
        <td>Mexico</td>
      </tr>
      <tr onclick="selectRow(this,'selected');">
        <td>John Doe</td>
        <td>USA</td>
      </tr>
      <tr onclick="selectRow(this,'selected');">
        <td>Shankra Pillai</td>
        <td>India</td>
      </tr>
    </tbody>
  </table>

Java Script:

    let prevIx
    let prevTr

    function selectRow(tr, className) {

        let ix = tr.rowIndex

        if (ix === prevIx) { // row already selected, so unselect
          tr.className = tr.className.replace(className,"")
          prevIx = null
          prevTr = null
        }
        else { // no selected rows

          if (prevTr) {
            // unselect previously selected row
            prevTr.className = prevTr.className.replace(className,"")
          }

          // select current row
          tr.className += className
          prevIx = ix
          prevTr = tr
        }
    }

CSS:

table .selected {
    background-color: #6ccbfb;
    color: #fff;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM