GLP
GLP

Reputation: 3675

how to set the visibility of an asp:checkbox in javascript

I have this asp:checkbox in my page, under certain condition, I want to hide it. I am trying to do it in JavaScript function by setting the style.display = 'none'. But somehow asp:checkbox is rendered as two html controls, input and label. The input is gone, but the label is still there. How do I properly hide the asp:checkbox in JavaScript then? Following is my code:

var checkBox= document.getElementById('ctl00_ContentPlaceHolder1_checkBox');
if (...)
{
    checkBox.style.display='none';
}

And following

<td>
<asp:CheckBox ID="checkBox" runat="server" Text="Test" onclick="..."/></td>

will be rendered as

<td><span disabled="disabled"><input id="ctl00_ContentPlaceHolder1_checkBox" type="checkbox" name="ctl00$ContentPlaceHolder1$checkBox" disabled="disabled" onclick="...;" /><label for="ctl00_ContentPlaceHolder1_checkBox">Test</label></span></td>

Upvotes: 2

Views: 4310

Answers (1)

Yuriy Galanter
Yuriy Galanter

Reputation: 39777

As MikeSmithDev said - you need to hide your label as well. In you code you can add following:

var checkBoxLabel = document.querySelectorAll('label[for=ctl00_ContentPlaceHolder1_checkBox]');

if (checkBoxLabel.length > 0) checkBoxLabel[0].style.display='none';

It locates the label by its for attribute and if it exists - hides it.

Or even easier - assuming that label always follows the input:

if (...)
{
    checkBox.style.display='none';
    checkBox.nextSibling.style.display='none';
}

This will hide the element following the checkbox - the label.

Btw, if this is applicable to you - on server-side it's a oneliner

checkBox.Style["display"] = "none"; // will render the control hidden

or

checkBox.Visible = false; // will not render control at all

Upvotes: 3

Related Questions