Link to home
Start Free TrialLog in
Avatar of mandi224
mandi224Flag for United States of America

asked on

Determining Checkbox Checked State via JavaScript / C# (ASP.NET)

I'm working on an ASPX page with C# codebehind. I have a checkbox that I want to use to show/hide toggle a div.

Below you'll see the code that I have right now, which WORKS but isn't exactly what I want.

The code I'm using just toggles the div, with no respect to the checkbox's checked state. This causes problems if the page posts back.

I want to be able to have a body onload event that checks the status of the checkbox and shows/hides the div accordingly (hide if UNchecked, show if checked).

I attempted doing this (currently from the checkbox onclick event, but I'd also like to use it in the body onload event):

function toggle_hide() {
            var div = document.getElementById('payment_address');

            if (document.getElementById("chkDifferentPmtAddress").checked == true)
                div.style.display = 'block';
            else
                div.style.display = 'none';
        }  

But I get an error "Object Required" on the "If" line in the above code.

This is what I currently have, which works, but doesn't take into account the checked status ...
// FROM THE CODEBEHIND:
protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        //Apply javascript to checkbox
        chkDifferentPmtAddress.Attributes.Add("onclick", "show_hide();");
}



// JAVASCRIPT IN HEADER OF THE PAGE

function show_hide() {
            var div = document.getElementById('payment_address');

            if(div.style.display == 'block')
              div.style.display = 'none';
            else
              div.style.display = 'block';
        }



// ASPX PAGE:

<asp:CheckBox ID="chkDifferentPmtAddress" runat="server" Text="Mail payments to a <strong>DIFFERENT address</strong>." />

<div id="payment_address" style="display:none;">
 <!-- Payment Address Info Goes Here -->
 <p>Whatever</p>
</div>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of prateekbahl
prateekbahl

you need the OnClientClick to fire the show_hide() function.
Avatar of mandi224

ASKER

Visual Studio didn't like the "OnClientClick" event put directly into the checkbox control as you suggested and wouldn't build. However, I was able to add:

chkDifferentPmtAddress.Attributes.Add("onclick", "show_hide();");

to the OnInit event for the page and that worked perfectly along with the javascript snippet that you supplied!  Thanks!!