Javascript Select/Unselect All Checkboxes
Another much used Javascript function is the one where we want to select/unselect a bunch of checkboxes on screen using client side scripting. Again, I inject the script in my code behind
private void InjectJavascript()
{
string toggleCheckboxes =
@"<script type=""text/javascript"">function SetAllCheckBoxes(formValue, checkValue)
{
var theForm;
var countElements;
var objElements;
theForm = document.forms[formValue];
if(!theForm)
return;
objElements = theForm.getElementsByTagName('input');
if(!objElements)
return;
countElements = objElements.length;
// set the check value for all check boxes
for(var i = 0; i < countElements; i++)
{
if (objElements[i].type == 'checkbox')
{
objElements[i].checked = checkValue;
}
}
}
</script>
";
ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleCheckboxes", toggleCheckboxes);
// Wire some javascript client-side events
rbtnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',true)");
rbtnUnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',false)");
}
Call this void in the Page Load.Add a couple of checkboxes and two radiobuttons to the page.
Name the radiobuttons "rbtnSelectAllCheckBoxes" and "rbtnUnSelectAllCheckBoxes".Give it a try.
Greetz,
G
private void InjectJavascript()
{
string toggleCheckboxes =
@"<script type=""text/javascript"">function SetAllCheckBoxes(formValue, checkValue)
{
var theForm;
var countElements;
var objElements;
theForm = document.forms[formValue];
if(!theForm)
return;
objElements = theForm.getElementsByTagName('input');
if(!objElements)
return;
countElements = objElements.length;
// set the check value for all check boxes
for(var i = 0; i < countElements; i++)
{
if (objElements[i].type == 'checkbox')
{
objElements[i].checked = checkValue;
}
}
}
</script>
";
ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleCheckboxes", toggleCheckboxes);
// Wire some javascript client-side events
rbtnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',true)");
rbtnUnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',false)");
}
Call this void in the Page Load.Add a couple of checkboxes and two radiobuttons to the page.
Name the radiobuttons "rbtnSelectAllCheckBoxes" and "rbtnUnSelectAllCheckBoxes".Give it a try.
Greetz,
G
Labels: Javascript
