Wednesday, 14 March 2007

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;

// 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