tags:

views:

107

answers:

4

Consider this scenario:

  • <asp:CheckBoxList> in a master page.
  • the goal is to have all checkboxes in this list to be checked on page load.
  • there are many checkbox lists on the page.

The markup:

    <asp:CheckBoxList runat="server" ID="chkSubscriptionType" 
        DataSourceID="myDS"
        CssClass="boxes" DataTextField="Name" DataValueField="Name"  />

renders to:

<input id="ctl00_cphContent_chkSubscriptionType_0" type="checkbox" name="ctl00$cphContent$chkSubscriptionType$0" />

Question: how can you use jQuery to check all boxes in this asp:CheckBoxList on document.ready? I see samples everywhere, but naming convention used by the master page throws off the samples in other places.

+3  A: 

ASP.NET's naming conventions are slightly frustrating. You can side-step them by wrapping your element in a span, and giving it a class. You can then use that span.class to focus your selector:

$(function(){
  // On dom-ready, all checkboxes in span.names will be checked
  $("span.names :checkbox").attr("checked", "checked");
});

<span class="names">
  <asp:CheckBoxList ... />
</span>
Jonathan Sampson
+1, but replace `:checkbox` with `input[type=checkbox]`
BlueRaja - Danny Pflughoeft
BlueRaja, why? `:checkbox` is the short-form of `input[type='checkbox']`.
Jonathan Sampson
Is :checkbox the short form of input[type='checkbox'] or just [type='checkbox']?http://docs.jquery.com/Selectors/checkbox seems to imply the latter by suggesting input:checkbox instead.
mark123
@mark123 There's only one type of checkbox in HTMl. `input[type='checkbox']`, `[type='checkbox']`, and `:checkbox` are all the same thing.
Jonathan Sampson
+3  A: 

Regardless of asp/php/ruby, etc, you should be able to do something like:

$(document).ready(function(){ 
      $("input[type=checkbox]").attr("checked", "checked");
});
Warren Krewenki
+4  A: 

Because of the naming container, the ID's will be auto-generated and messed up, as you mention. You can use an attribute filter to select all elements that contain the part that you do know, that is, "chkSubscriptionType". For example:

$("input[id*=chkSubscriptionType]").attr("checked", "checked");

The *= means "contains".

womp
If the css class is specific to the checkboxes in question, that could be used in the selector as well.
grenade
A: 

Try this check/uncheck all checkboxes function. http://praveenbattula.blogspot.com/2009/09/checkuncheck-all-checkboxes-in-jquery.html

Rare Solutions