In this JSFiddle (with the problem code commented out) the first click in an empty cell sets a value in a hidden input and sets the bgcolor of the cell to green. A click in a second empty table cell sets the value of another hidden input and changes the second cell bgcolor to red.
Now, based on feedback from another SO question I have tried to implement a check by looping through an array (All the commented out code) of all td's in the table to see if onclick, any cell already has a bgcolor set to green/red respectively and if true, set the bgcolor to empty/blank to allow for the NEW cell selection to get the bgcolor , so there should always be only 1 green block and 1 red block. Can someone explain to me how I am implementing the loop and check wrong and not getting the expected result.
the array looping works here -jsfiddle when not part of the existing code. But when I add it to code where it's needed, it does not work.
HTLM
<div id="starget"></div>
<div id="etarget"></div>
<table width="100%" id="test">
<thead>
<tr>
<th>Tech</th>
<th>0800</th>
<th>0900</th>
<th>1000</th>
<th>1100</th>
<th>1200</th>
</tr>
</thead>
<tr>
<td>Bill</td>
<td>XXX</td>
<td onclick="res(0900,this);"></td>
<td>XXX</td>
<td>XXX</td>
<td onclick="res(1200,this);"></td>
</tr>
</table>
SCRIPT
var x = 0;
var click = 0;
/* tdElements = document.getElementsByTagName("td"); */
/* I have tried the tdelements array inside and outside of the function */
function res(zz,el) {
if (click == 0) {
/* for(var key in tdElements) {
if (tdElements[key].style.backgroundColor=="green") {
tdElements[key].style.backgroundColor="";
}
} */
document.getElementById('starget').innerHTML=zz;
click = 1;
el.style.backgroundColor='green';
}
else {
/* for(var key in tdElements) {
if (tdElements[key].style.backgroundColor=="red") {
tdElements[key].style.backgroundColor="";
}
} */
document.getElementById('etarget').innerHTML=zz;
click = 0;
el.style.backgroundColor='red';
}
}
for ... inloops for iterating through arrays or array-like objects. Use a numeric index..lengthproperty of the node list returned fromgetElementsByTagName()will tell you..lengthreturns lets say 5o that I should write this checkdocument.getElementsByTagName("td")[0].style.backgroundColor=="green";50 times?forloop with a numeric index -for (var i = 0; i < tdElements.length; ++i)and operate ontdElements[i]