Reputation: 27
I have two checkboxes. If the first checkbox checked, the second checbox will be disabled and if the first checkbox unchecked, the second checkbox will be enabled.
<div class="data">
<asp:CheckBox ID="firstCheckBox" runat="server" CssClass="LabelText" EnableViewState="False" AutoPostBack="True" />
</div>
<div class="data">
<asp:CheckBox ID="secondCheckBox" runat="server" CssClass="LabelText" EnableViewState="False" AutoPostBack="True" />
</div>
Here is my control part at the Page_Load;
if (firstCheckBox.Checked)
{
secondCheckBox.Enabled = false;
}
else
{
secondCheckBox.Enabled = true;
}
When I checked the firstcheckbox, nothing happens to the secondcheckbox. After I checked the second checkbox, secondcheckbox has been checked and disabled.
What am I missing?
Upvotes: 1
Views: 872
Reputation: 278
You can use javascript
to enable or disable checkbox.
Here firstCheckBox
& secondCheckBox
are the id's of your checkbox.
if(document.getElementById("firstCheckBox").checked = true)
document.getElementById("secondCheckBox").disabled = true;
else
document.getElementById("secondCheckBox").disabled = false;
Upvotes: 1
Reputation: 24957
I assumed that you want to set Enabled
state of second checkbox in server-side, hence you should handle CheckedChanged
event from first checkbox like this example:
private void firstCheckBox_CheckedChanged(object sender, EventArgs e)
{
secondCheckBox.Enabled = !firstCheckBox.Checked;
}
The problem why the checkbox checked
event handler is not triggered is because you're putting the logic inside Page_Load
event instead of CheckedChanged
event from first checkbox.
Similar issue:
If one checkbox is checked, set the other to unchecked
Upvotes: 0
Reputation: 137
You can do it with checkBox CheckChanged event. Please remove condition from load event of your form and add below code.
<div class="data">
<asp:CheckBox ID="firstCheckBox" runat="server" CssClass="LabelText" EnableViewState="False" AutoPostBack="True" OnCheckedChanged="CheckBox1_Check_Clicked" />
</div>
<div class="data">
<asp:CheckBox ID="secondCheckBox" runat="server" CssClass="LabelText" EnableViewState="False" AutoPostBack="True" OnCheckedChanged="CheckBox2_Check_Clicked" />
</div>
protected void CheckBox1_Check_Clicked(Object sender, EventArgs e)
{
if(CheckBox1.Checked==true)
{
CheckBox2.Enable=false;
}
else
{
CheckBox2.Enable=true;
}
}
protected void CheckBox2_Check_Clicked(Object sender, EventArgs e)
{
if(CheckBox2.Checked==true)
{
CheckBox1.Enable=false;
}
else
{
CheckBox1.Enable=true;
}
}
So you should have two CheckChanged events on each checkbox individual. Autopostback true. Same you can do with only one event if you apply some logic.
Upvotes: 0