DotNetNuke, ASP.NET, Web Development Blog

DotNetNuke: Hiding and Showing Checkbox with and Javascript

As I build out the settings for DotNetNuke modules, I only like to display settings that are relevant to the other selections the user has made. The best way to do this is with Javascript so users don't have to wait for a postback everytime they change a relevant control.

In trying to put these things in place, I often find the code often doesn't work quite the way I expect (or at least used to expect) it to. The issue usually has to do with the way renders controls. I usually find I have to dig into the source view a bit to see exactly how rendered something and then fiddle a bit to get everything working right.

Here, I'll describe, one particular case where I had two checkboxes linked. The 2nd checkbox should only be displayed when the first checkbox is checked...

When you add an <asp:checkbox ...> tag to a page, .NET actually renders two separate tags, an input for the checkbox and a label for the text. In order to hide / show the control when the other checkbox gets checked / unchecked, I added some JavaScript to trigger on the onclick event in the page load event.

chk1.Attributes.Add("onclick", String.Format(showhidejs, chk1.ClientID, chk2.ClientID))

The problem with doing that is that will only affect the checkbox tag and not the corresponding label. I'll discuss the fix for this below, but first more of the problem...


Also in the load, in order to ensure chk2 was properly hidden if chk1 was unchecked, I did a"display") = "none".

When you look at the html rendered by for this, you'll see that it actually wraps both of the tags (checkbox and label) in a span with the display: none style.

When testing this, it seemed all sorts of odd things were occurring. But, if you actually looked at the render code, it all began to make sense. Javascript and .NET were actually applying styles to different elements and so they were interacting in all sorts of odd ways depending on the various settings.

The fix for all this was really quite easy. All I had to do was explicitly wrap the checkbox in my own span tag and then explicitly reference that span tag from both ASP.NET and Javascript. Then, everything worked as expected.


Leave a Comment
Email: (not displayed)

Enter the code shown above:

Return to previous page