Solved

ASP.NET Enable/Disbale Textbox based on Checkbox

Posted on 2009-05-16
2
904 Views
Last Modified: 2012-05-07
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
Comment
Question by:ITHelper80
  • 2
2 Comments
 
LVL 6

Accepted Solution

by:
rdogmartin earned 500 total points
ID: 24404947
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
 
LVL 6

Expert Comment

by:rdogmartin
ID: 24404950
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

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question