...

View Full Version : Trying to get checkbox state but not reading



putha
10-13-2011, 06:24 PM
I am trying to make a simple alert come up stating a checkbox is checked when it changes, and then another alert for when the checkbox is unchecked.

Problem is, only the alert for when the box is checked is coming up.

Anyone know why?


function displayCheckPopUp()
{
if(document.activeElement.checked=true)
{
alert("A check box has been selected");
}
else if(document.activeElement.checked=false)<!--if(document.getElementById().checked=false)-->
{
alert("****");
}
}


<input type="checkbox" name="Checkbox 1" value="Checkbox 1" id="first_cbox" onchange="displayCheckPopUp(this)" /> <p class="custom_style2"> Checkbox 1 </p>

DaveyErwin
10-13-2011, 08:04 PM
if(document.activeElement.checked=true)
should be ....
if(document.activeElement.checked==true)

also document.activeElement
doesn"t work for ie7

Old Pedant
10-13-2011, 10:57 PM
You can avoid using activeElement (which doesn't work in MSIE, as Davey said) by actually *USING* the this reference that you passed. Also, avoid putting spaces and other non-standard name characters in names and ids.


<label>
<input type="checkbox" name="Checkbox1" value="Checkbox 1"
onchange="displayCheckPopUp(this)" />
<p class="custom_style2"> Checkbox 1 </p>
</label>

and then simply:

function displayCheckPopUp(chkbox) /* chkbox is from the this */
{
if( chbox.checked ) /* no need to compare vs. true! it's already true or false */
{
alert("The checkbox named '" + chbox.name + "' has been selected");
} else {
alert("The checkbox named '" + chbox.name + "' has been DE-selected");
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum