ASP.NET - Code Samples - Disable CheckboxList Items

ASP.NET CheckBoxList Item Disable Javascript Workaround

The Reason:

The ASP.NET Checkboxlist control provides a way for you to add checkboxes as listitems. While this control makes working with multiple checkboxes much easier it lacks one very key item, an enable property. The only workaround for this at the moment is to add a javascript function which does the enabling and disabling automatically. Below is javascript that will enable or disable whatever items you choose. This code was based upon Code by Ken G Young.

The Code:

	//Add This Code To the HTML directly 
	// checkboxlistID = id of the checkboxlist
	// chkarray = array of indexes to set enable or disable
	// disable = true to disable
	<script language=javascript>
	function disableListItems(checkBoxListId, chkArray, disable)
	{
		// Get the checkboxlist object.
		objCtrl = document.getElementById(checkBoxListId);
	    
		// Does the checkboxlist not exist?
		if(objCtrl == null)
		{        return;
		}

		var i = 0;
	    

		// iterate through listitems that need to be enabled or disabled
		for(i = 0; i<chkArray.length; i++)
		{
			objItem = document.getElementById(checkBoxListId + '_' + chkArray[i]);

			if(objItem == null)
			{
				continue;
			}

				// Disable/Enable the checkbox.
				objItem.disabled = disable;
				// Should the checkbox be disabled?
				objItem.checked = false;

		}
	}
	</script>

	
	'Add Code to the page load event (this demonstrates disabling the 2nd and 3rd items)

	'Disable on intial Page Load
	 If Not Me.IsStartupScriptRegistered("doit") Then
		Me.RegisterStartupScript("doit", "<script language=""javascript"">disableListItems('checkBoxList1',new Array(1,2),true);</script>")
	 End if

	'Disable on checkboxlist click
	CheckBoxList1.Attributes.Add("onclick", _
            "disableListItems('checkBoxList1',new Array(1,2),true)")
About this page: