views:

504

answers:

2

I have a GridView on an .ascx. I have an asp:Checkbox CheckAll checkbox in the header template for a column and then a checkbox in the ItemTemplate. I would like to add the functionality so that when I check the checkbox in the Header, it will check or uncheck all of the checkboxes in the GridView.

How do I do this with JQuery? I would then like to also add reverse functionality so that when I uncheck a checkbox within the GridView that it unchecks the checkbox in the Header.

A: 

You can play with the Checkbox 'CheckAll' ID and the rows' classes.

For example, you can have a control Id "chkSelectAllNone" (notice that this is going to change in the client for something like 'Ctl001_chkSelectAllNone') and you can assign the rows classes with the css class "select-row".

Then, create a jQuery script in the aspx (or writing it from the code behind) to handle the toggle Select All/None, like this one:

$("#<%= chkSelectAllNone.ClientID %>").click(function(){
$(".select-row").attr("checked", $("#<%= chkSelectAllNone.ClientID %>").attr("checked"));
});

Hope it helps.

Sebastian
Will <%= chkSelectAllNone.ClientID %> this really return the ClientID because this control is in the HeaderTemplate of the GridView and not declared outside of the GridView?
Adam
The fact here is that you need the client ID for that checkbox for binding the click event and execute the javascript. Turn that string into whatever gives you the client control ID.
Sebastian
A: 

I'm not sure if GridViews render a th, but if they do this should get you close:

$("th :radio").click(function() {
  if($(this).is(":checked")) {
    $("td :radio").attr("checked", "checked");
  }
});

$("td :radio").click(function() {
  var attr = $("td :radio").not(":checked").length ? "" : "checked";
  $("th :radio").attr("checked", attr);
});
Andy Gaskell