Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap

Q583 How can I count the time in seconds that a checkbox is really checked?

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">

<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
            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

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

Feedback on 'Q583 How can I count the time in seconds that a checkbox is really checked?'

©2018 Martin Webb