Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Date | Q583 [ previous next ]

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

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>

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


Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.