Posts
16
Comments
96
Trackbacks
18
July 2006 Entries
Enabling/disabling asp.net checkboxes through javascript

The problem:

You want to have a web form with multiple checkboxes, and have some of them be enabled or disabled depending on whether a certain checkbox is checked (or radio button selected, or what have you).

At first glance, this seems fairly simple; you can just do:

<%=myCheckBox.ClientID%>.disabled = false;

in javascript.

The problem comes when you, on the server side, disable the checkbox by default. (NB: this pertains to ASP.Net 2.0, it may work differently in 1.x). The problem is that an <asp:checkbox /> control gets rendered out like this:

<span><input type='checkbox'></span>

The real problem comes when you have a checkbox like this: <asp:checkbox enabled=”false” />. This gets rendered out like this:

<span disabled='disabled'><input type='checkbox' disabled='disabled'></span>

Can you see the problem? In our javascript, when we enable the input, we're not enabling the surrounding span. As it happens, in FireFox, this doesn't seem to be an issue (the checkbox will be enabled as you would expect). In IE6, however, the checkbox will be disabled because the surrounding span is disabled.

To get around this, you can do the following instead of saying myCheckBox.Enabled = false in your code-behind:

myCheckBox.InputAttributes.Add(”disabled”, “disabled”);

(There's also a “LabelAttributes” property of the checkbox, if your control has text that you want to give attributes to explicitly).

Hope this helps!

posted @ Thursday, July 27, 2006 10:10 PM | Feedback (46)
News