GSharper

Wednesday, 14 March 2007

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

Labels:

Javascript Select/Unselect checkbox

Every time I have to use JS I get iritated because I always have to look it up on the Net. Let's put it on my blog so I can find it easier.

The problem I had to deal with was creating a JS function to select/Unselect a checkbox. I wrote the JS function in my code behind


private void InjectJavascript()
{

string toggleCheckbox = @"<script type=""text/javascript"">
function SelectUnSelectCheckBox(select)
{
var myCheckBox = document.getElementById('" + MyCheckBox.ClientID + "');";

toggleCheckbox += @" myCheckBox.checked = select;
}</script>";


// Register the javascript
ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleCheckbox", toggleCheckbox);

// Wire some javascript client-side events
rbtnSelectCheckBox.Attributes.Add("onclick", "SelectUnSelectCheckBox(true)");
rbtnUnSelectCheckBox.Attributes.Add("onclick", "SelectUnSelectCheckBox(false)");
}


Call InjectJavascript in the Load of the form. Put a checkbox "MyCheckBox" and two radiobuttons "rbtnSelectCheckBox" and "rbtnUnSelectCheckBox" on the form.

That's it

Greetz,
G


Labels: