Introduction
1. Add a CheckBoxList to your ASP.NET WebForm and give it an ID of checkBoxListTest.
2. Add a call to the LoadCheckBoxList in the Page_Load event.
3. Add the LoadCheckBoxList method to your webpage class.
4. Add the JavaScript function inside the head of the HTML.
ASP.NET CodeBehind
private void Page_Load(object sender, System.EventArgs e)
{
if(!this.IsPostBack)
{
LoadCheckBoxList();
}
}
private void LoadCheckBoxList()
{
this.checkBoxListTest.Attributes.Add("onclick",
"disableListItems('checkBoxListTest', '2', '3')");
// Add three items to the CheckBoxList.
for(int i=0; i < item =" new">
This method adds the onclick function disableListItems to the CheckBoxList attributes collection. The function will disable all the items except for the last item in the list when it is checked. The method also adds three items to the CheckBoxList.
JavaScript Function
function disableListItems(checkBoxListId, checkBoxIndex, numOfItems)
{
// Get the checkboxlist object.
objCtrl = document.getElementById(checkBoxListId);
// Does the checkboxlist not exist?
if(objCtrl == null)
{
return;
}
var i = 0;
var objItem = null;
// Get the checkbox to verify.
var objItemChecked =
document.getElementById(checkBoxListId + '_' + checkBoxIndex);
// Does the individual checkbox exist?
if(objItemChecked == null)
{
return;
}
// Is the checkbox to verify checked?
var isChecked = objItemChecked.checked;
// Loop through the checkboxes in the list.
for(i = 0; i < numOfItems; i++)
{
objItem = document.getElementById(checkBoxListId + '_' + i);
if(objItem == null)
{
continue;
}
// If i does not equal the checkbox that is never to be disabled.
if(i != checkBoxIndex)
{
// Disable/Enable the checkbox.
objItem.disabled = isChecked;
// Should the checkbox be disabled?
if(isChecked)
{
// Uncheck the checkbox.
objItem.checked = false;
}
}
}
}
The above code is the JavaScript function that is invoked by the onclick event of the CheckBoxList.
1 comment:
gr8 article!!!
Post a Comment