View Full Version : Calendar table cell onclick toggling

03-20-2012, 04:08 PM
Long time reader of dynamicdrive and very much appreciate all the create info here, first time actual posting though.

I have a table calendar dynamically generated in php with class styles for weekends/holidays, weekdays and today. I'd like to be able to toggle a cell's background color as the selected day, thereby becoming "today". I've been searching for hours on end on ways to do this with Javascript but almost all solutions are for changing a cell background color and not reverting the currently toggled "today" cell. Only one cell in the calendar month view can ever be "today".

I'm really not very good with Javascript but it seems I need to cycle through the td's on the onclick event and revert the classes of all but the selected day.

I believe this is the closest I've found but I couldn't get it to work at all

<script type="text/javascript">
function select(which)
var tds = document.getElementById("caltable").getElementsByTagName("td");
for ( var t = 0; t < tds.length; ++t )
tds[t].style.backgroundColor = ( which == td ) ? "red" : "blue";

Ideally however instead of specifically toggling the background color, I'd like to save the cell's current class in a variable, switch it, then when another cell is selected, revert that previous cell to its old class and rinse and repeat for the new cell. I achieved this on a single cell (saving previous state) so I could toggle multiple cells all knowing their previous state but couldn't revert other toggled ones when selecting a new one.