Javascript to check whether a checkbox is being checked or unchecked
You should be evaluating against the checked property of the checkbox element.
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
// if the current state is checked, unchecked and vice-versa
if (arrChecks[i].checked)
{
arrChecks[i].checked = false;
} else {
arrChecks[i].checked = true;
}
} else {
arrChecks[i].checked = false;
}
}
The value
attribute of a checkbox
is what you set by:
<input type='checkbox' name='test' value='1'>
So when someone checks that box, the server receives a variable named test
with a value
of 1
- what you want to check for is not the value
of it (which will never change, whether it is checked or not) but the checked
status of the checkbox.
So, if you replace this code:
if (arrChecks[i].value == "on")
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
With this:
arrChecks[i].checked = !arrChecks[i].checked;
It should work. You should use true
and false
instead of 0
and 1
for this.