Refactor Code

  • Gravatar
    Selecting All CheckBoxes of the CheckBoxList Control

    by azamsharp on 5/10/2008 10:37:03 AM
  • I am using ASP.NET CheckBoxList control and needs to check all the checkboxes for that control and uncheck if they are already check. So, I gave JQuery a try and here is the code that I came up with.
  • <asp:CheckBoxList ID="chkList" runat="server">
    <asp:ListItem Text="Item 1" Value="Item 1"></asp:ListItem>
    <asp:ListItem Text="Item 2" Value="Item 2"></asp:ListItem>
    <asp:ListItem Text="Item 3" Value="Item 3"></asp:ListItem>

    </asp:CheckBoxList>

    <input type="button" id="btn_CheckAll" value="check all" />

    $(document).ready(function()
    {
    // attach the event to the button control
    $("#btn_CheckAll").click(function()
    {
    // i want to check all the checkboxes contained in the chkList control
    $("#chkList").find("input[@type=checkbox]").each(function()
    {
    if(!this.checked)
    {
    this.checked = true;
    return;
    }

    this.checked = false;

    });

    });

    });
  • Refactor it!
  • Gravatar
    Here is the much simplified version:
    by azamsharp on 5/10/2008 11:07:30 AM
  • // attach the event to the button control
    $("#btn_CheckAll").click(function()
    {

    $("#chkList input:checkbox").attr("checked",function()
    {
    this.checked = !(this.checked == true)
    });


    });
  • Gravatar
    if you have the checkboxes in a container div with a specific class, then you can make your life easier.
    by subdigital on 5/11/2008 10:05:26 AM
  • <div class="container">
    <input type="checkbox" .... />
    ...more
    </div>

    function checkBoxes()
    {
    $(".container input['type=checkbox']).attr("checked",
    function(cb) { cb.checked = !cb.checked });
    }
Please log in to refactor the code! Login