Solved

ASP.NET Enable/Disbale Textbox based on Checkbox

Posted on 2009-05-16
2
903 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
Comment Utility
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
Comment Utility
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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
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…
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…

728 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now