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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With