Thursday, February 23, 2012

Javascript to count selected items in CheckBoxList

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
CheckBoxList1.Attributes.Add("onclick", "javascript:CopyNumItemsToTextBox();")
End Sub

--------------------------------

function CopyNumItemsToTextBox() {
//This function updates TextBox1 with the number of items checked when an item is checked/unchecked
//Get the checkbox object
var textBox = document.getElementById("TextBox1");
//Get the checkboxlist object
var checkBoxList = document.getElementById("CheckBoxList1");
//Get the number of checkboxes in the checkboxlist
var numCheckBoxItems = checkBoxList.cells.length;
var numItemsChecked = 0;

for(i=0; i<numCheckBoxItems; i++)
{
//Get the checkboxlist item
var checkBox = document.getElementById(checkBoxList.id + '_' + [i]);
//Check if the checkboxlist item exists, and if it is checked
if(checkBox!=null && checkBox.checked){ numItemsChecked = numItemsChecked + 1; }
}
//Set the text box to the number of items checked in the checkboxlist
textBox
.value = numItemsChecked;
}

No comments:

Post a Comment