Monday 20 April 2009

Using jQuery to toggle visibility of an ASP.NET textbox based on an ASP.NET DropDownList Control

My requirement was to display/hide associated comments boxes depending on what was entered in a "yes/no/not available" style dropdown.

To implement this, I made use of the following

  1. Hooking up the click and load events of the dropdowns via jQuery so that the comments text boxes would show correctly when the page initially loaded, or when the selected value changed
  2. Putting spans around groups of controls that I wanted to hide/show to use in the jQuery selectors e.g. span with class of "pricing" for all controls that should be hidden/ shown based on the Pricing dropdown list.
  3. In the common javascript handler, passing through the dropdownlist control itself, along with the class which should be used by the jQuery selectors to be hidden/shown.

STEP 1 - Common Code (CommentFieldHelper.js) - add this as a link ref to your masterpage/base page/page/control

/*Javascript file for hide/show of Yes/No/NA controls and their asssociated comment fields*/
/* Version 0.1 - Original*/

//Initialise handlers when the control is loaded and on change to show/hide associated comment field
function initCommentFieldVisibilityHandlers(sourceControl, classToHide, areNotesShownWhenNo)
//Hook up change handler
function() {
changeCommentFieldVisibility($(this), classToHide, areNotesShownWhenNo);

//Hook up load handler
changeCommentFieldVisibility(sourceControl, classToHide, areNotesShownWhenNo)

//Set visibility of controls with the "classToHide" class defined on them (typically span class="myclassname")
function changeCommentFieldVisibility(sourceControl, classToHide, areNotesShownWhenNo) {

var selected = $('option:selected', sourceControl).text();

if (areNotesShownWhenNo == false) {
if (selected == 'No') {
$('span.' + classToHide).fadeOut();
else {
$('span.' + classToHide).fadeIn();
else {
///If areNotesShownWhenNo and selected item is not No, then hide.
if (selected != 'No') {
$('span.' + classToHide).fadeOut();
else {
$('span.' + classToHide).fadeIn();


STEP 2 - Simple inline in control/page/master page:
<script language="javascript" type="text/javascript">

//Place in your user control/page/masterpage
$(document).ready(function() {
//Initialise hide and show of associated comments textbox onload/onchange of dropdown list
$('#<%=ProposalAssessmentFormView.FindControl("FundingStateInfrastructureRelevantDropDownList").ClientID %>'),
'fundingStateInfrastructureRelevant', false);



STEP 3 - Add controls/divs/spans with the correct class tags so they will be shown/hidden based on the selected value of the dropdown list.

No comments: