AJAX and the .NET framework CheckBox control

Because the .NET framework controls didn't plan in advance to be able to incorporate ASP.NET AJAX features into the framework, there can be certain things that make working with .NET controls harder.  Take, for instance, the checkbox control.  While this control is simple, to show or hide the checkbox is not as easy as simply accessing the element by it's ID and setting the style.display property to none.

A checkbox renders, with text, as:

<input type="checkbox" ../>
<label for="checkID">text</label>

So if you try to do this to hide the checkbox:

var check = $get("<%= checkID.ClientID %>");
check.style.display = "none";

The label element will still be visible.  Using a separate <asp:Label> element and using $get() to return the reference to the label works as a way to get the checkbox label and show/hide it as well.  Alternatively, the checkbox is wrapped with a <span> tag as such:

<span>
  <input ..>
  <label ..>
</span>

So if you want to show/hide a checkbox and the associated text, you can also do:

var check = $get("<%= checkID.ClientID %>");
check.parentNode.style.display = "none";

The parentNode method returns the reference to the parent node (the parent span tag, as the check object is referencing the <input> element).  And thus, both the label/input tag are shown/hidden.

Published Saturday, January 03, 2009 4:52 AM by bmains
Filed under: ,

Comments

No Comments