You are here: irt.org | FAQ | JavaScript | Date | Q583 [ previous next ]
Tricky this one. In some older browsers there isn't an onClick event handler for checkboxes. Therefore you'd need to continually check the status of the checkbox if you wish to capture the change from checked to non-checked and vice versa:
<form name="myForm"> <input name="myCheckBox" type="checkbox"> <input name="totalTime" type="text"> </form> <script language="JavaScript"><!-- function timer() { if (document.myForm.myCheckBox.checked != isitchecked) { // checkbox clicked isitchecked = document.myForm.myCheckBox.checked; now = new Date() if (isitchecked) starttime = now.getTime(); // now checked so reset starttime else document.myForm.totalTime.value = 0; // no longer checked so reset } else { // not clicked since last check if (isitchecked) { // still checked now = new Date(); totaltime = now.getTime() - starttime; // totaltime in milliseconds that checkbox has been checked. document.myForm.totalTime.value = totaltime/1000/60; // time in minutes } } setTimeout('timer()',100); } var totaltime = 0; document.myForm.totalTime.value = totaltime; var isitchecked = document.myForm.myCheckBox.checked; if (isitchecked) { now = new Date() starttime = now.getTime(); // if intial stae is check then set starttime } timer(); // start constant monitoring of checkbox //--></script>