Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New to the CF scene
    Join Date
    Oct 2011
    Posts
    6
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Trying to get checkbox state but not reading

    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?

    Code:
    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("****");
    	}
    }
    Code:
    <input type="checkbox" name="Checkbox 1" value="Checkbox 1" id="first_cbox" onchange="displayCheckPopUp(this)" /> <p class="custom_style2"> Checkbox 1 </p>

  • #2
    Regular Coder
    Join Date
    Aug 2010
    Posts
    972
    Thanks
    19
    Thanked 212 Times in 210 Posts
    if(document.activeElement.checked=true)
    should be ....
    if(document.activeElement.checked==true)

    also document.activeElement
    doesn"t work for ie7
    Last edited by DaveyErwin; 10-13-2011 at 07:09 PM.

  • #3
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,542
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    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.
    Code:
    <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");
    	}
    }
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •