• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 913
  • Last Modified:

ASP.NET Enable/Disbale Textbox based on Checkbox

I have two .Net controls on a form (textbox and checkbox), how can i disable the textbox when the checkbox is checked and also enable it if the user unchecks it?

I dont want to do a postback so I assume this needs to be done via Javascript.
0
ITHelper80
Asked:
ITHelper80
  • 2
1 Solution
 
rdogmartinCommented:
This solution assumes you have MS AJAX. First, add a click event handler to the checkbox control:

<asp:CheckBox ID="chk1" runat="server" onclick="chk1_Click()" Text="My checkbox" />

Then implement your event handler:

 function chk1_Click()
{
  handleCheckBoxClick();
}

function handleCheckBoxClick()
{
  var chkbx = $get('<%= chk1.ClientID %>');
  var txtbx = $get('<%= txtbx.ClientID %>');

  txtbx.disabled = (!chkbx.checked || chkbx.disabled);
}

You may need to disable the textbox when the page first loads. To do this, add a function that runs after page load:

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(myPageLoad);

function myPageLoad(sender, args)
{
  handleCheckBoxClick();
}




0
 
rdogmartinCommented:
I should also mention that disabled controls do not post their state during postbacks, so you will not be able to read the text in a disabled textbox on the server side. Hopefully this isn't a requirement.
0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now