CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   "Traffic light" html cells with javascript issue (http://www.codingforums.com/showthread.php?t=287021)

happybanana 02-04-2013 12:16 PM

"Traffic light" html cells with javascript issue
 
Hi,

I've got three html table cells setup so when I click on one of them I simulate a traffic light system (and call some ajax to post the result).

<td onclick=\"togCell('green'); makemyPOSTRequest('$myvar', '3')
<td onclick=\"togCell('amber'); makemyPOSTRequest('$myvar', '2')
<td onclick=\"togCell('red'); makemyPOSTRequest('$myvar', '1')

The javascript I'm using has worked fine, up until the point that I now have the result from the traffic light saved in a database. When my php script loads it checks the result and changes the background accordingly when the page loads.

The issue is that say the traffic light loads as red, now if I click on yellow the two cells yellow and red .. if that makes sense. How do I nuetralise the red? ... or any other color. Here's the javascript I'm using:

Code:

<script type=\"text/javascript\">
var el
function togCell(col){
if (typeof event!=='undefined')
 el=event.srcElement

 for (var i = 0; i < el.parentNode.cells.length; i++)
  el.parentNode.cells[i].style.backgroundColor=''
  el.style.backgroundColor=col
}
if (window.addEventListener)
window.addEventListener('click', function(e){el=e.target}, true)
</script>


Philip M 02-04-2013 04:17 PM

Use braces with your for statement (and if statement) - they are not optional. And every Javascript statement should be followed by a semi-colon ; except function, if, else, for, while, do, switch, and try.

Code:

for (var i = 0; i < el.parentNode.cells.length; i++) {
  el.parentNode.cells[i].style.backgroundColor='';
  el.style.backgroundColor=col;
}

"The louder he talked of his honour, the faster we counted our spoons." - Samuel Johnson

happybanana 02-05-2013 10:41 AM

Thanks for that ... can't believe I missed that. Actually can't believe it was working at all in the first place!

OK, so I changed this line and added the color blue to make it obvious what's going on in my program.

el.parentNode.cells[i].style.backgroundColor='blue';

For some reason it highlights the entire row but doesn't change the bgcolor in the code piece I'm using to indicate a saved traffic light from the database (here):

Code:

<td bgcolor=\"green\" onclick=\"togCell('#green'); makePOSTRequest('$javvar', '1')\">&nbsp</td>
Any ideas why it's not changing the bgcolor?

happybanana 02-05-2013 10:47 AM

*slaps head* never mind ... just solved it

changing el.parentNode.cells[i].style.backgroundColor='';

to el.parentNode.cells[i].style.backgroundColor='white';

surprisingly solves it :)


All times are GMT +1. The time now is 07:11 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.