Check All Checkboxes with JQuery[转]

Posted At : July 9, 2008 10:16 PM | Posted By : Adrian J. Moreno
Related Categories:  JQueryJavascript

I've been working with JQuery quite a bit lately and I'm aggravated that I didn't pick it up sooner. Someone on the DFW CFUG mailing list asked for a quick example of why they should use it. Another post on the JQuery list asked how to create a "Check All" box using JQuery. I decided to expand on the "check all" example I posted to the CFUG list to show how things have progressed from old school Javascript to JQuery.

Working Examples

So here's a basic form with 2 series of checkboxes.

myCByourCB
 A
 B
 C
 D
 E
 F
 G
 H
 I
 J
 K
 L

1.  

2.  

3.  Check All checkboxes with JQuery Automatically

4a.  Check All named "myCB" with JQuery onclick.

4b.  Check All named "yourCB" with JQuery onclick.

5a.  JQuery Check All Left Column

5b.  JQuery Uncheck All Right Column

Break It Down: Old School to JQuery

Each column in the form has a group of checkboxes of the same name. When you have multiple form elements of the same name, they represent an Array in the Document Object Model (DOM).

<form id="myForm" name="myForm" action="" method="post">
    <table border="1">
       <tr>
          <td>myCB </td>
          <td>yourCB </td>
       </tr>
       <tr>
          <td>
             <input type="checkbox" name="myCB" value="A" /> A <br />
             <!-- etc. -->
          </td>
          <td>
             <input type="checkbox" name="yourCB" value="G" /> G <br />
            <!-- etc. -->
          </td>
       </tr>
    </table>

1. Old School

The first set of buttons will check and uncheck all checkboxes named myCB.

<input type="button" name="ca_v1_on" value="Check All myCB" οnclick="checkAll(1);"/>
<input type="button" name="ca_v1_off" value="Uncheck All myCB" οnclick="checkAll(0);"/>

These buttons call the Javascript function checkAll() when you click them. This function determines if there is more than one form element named myCB. If so, then it loops through those elements, setting their checked attribute to true or false based on the value of flag. If there's only one, then it sets that one element's checked attribute to true or false based on the value of flag.

checkAll() - Old School Javascript
function checkAll(flag)
{
   if ( document.myForm.myCB.length )
   {
      for (var x = 0; x < document.myForm.myCB.length; x++)
      {
         if (flag == 1)
         {
            document.myForm.myCB[x].checked = true;   
         }
         else 
         {
            document.myForm.myCB[x].checked = false;
         }
         
      }
   }
   else
   {
      if (flag == 1)
      {
         document.myForm.myCB.checked = true;            
      }
      else 
      {
         document.myForm.myCB.checked = false;
      }
   }
}

That's a boat load of code. We could remove some of the hard coded bits like this:

function checkAll(id, name, flag)
{
   if ( document.forms[ id ].elements[ name ].length )
    /* ... */
}

or even using

function checkAll(id, name, flag)
{
   if ( document.getElementsById( id ).elements[ name ].length )
    /* ... */
}

but it's still a lot of code.

2. Stepping into JQuery

The second set of buttons will check or uncheck all checkboxes named myCB using JQuery.

<input type="button" name="ca_v2_on" value="JQuery Check All myCB" οnclick="jqCheckAll('myForm', 'myCB', 1);"/>
<input type="button" name="ca_v2_off" value="JQuery Uncheck All myCB" οnclick="jqCheckAll('myForm', 'myCB', 0);"/>

These buttons call the Javascript function jqCheckAll(). This function takes three arguments:

  1. The ID of the form that contains the checkboxes.
  2. The name of the checkboxes that will be checked.
  3. A flag to check (1) or uncheck (0) each checkbox.
jqCheckAll() - JQuery
function jqCheckAll( id, name, flag )
{
   if (flag == 0)
   {
      $( "form#" + id +  " INPUT[@name=" + name +  "][type='checkbox']").attr('checked', false);
   }
   else
   {
      $( "form#" + id +  " INPUT[@name=" + name +  "][type='checkbox']").attr('checked', true);
   }
}

Let's break down the JQuery code's syntax:

$( "form#" + id +  " INPUT[@name=" + name +  "][type='checkbox']").attr('checked', false);
  1. $("form#" + id: Find a form whose ID is the value of the id argument.
  2. " INPUT[@name=" + name + "]: now find any INPUT element whose name matches the value of the name argument.
  3. [type='checkbox']: make sure that form element is of type "checkbox".
  4. .attr('checked', false);: set that element's checked attribute to true or false based on the value of the argument flag.

Ok, so that's a LOT less code. We also don't have to worry about there being one element or an array of elements. JQuery handles that for us.

3. Let JQuery handle things automatically.

Our third option for checking all these checkboxes involves a single form element. We don't even have to add any onclick or onchange events directly to the checkbox. JQuery will let us assign that outside of the HTML.

<input type="checkbox" name="checkAllAuto" id="checkAllAuto"/> Check All checkboxes with JQuery Automatically

Here we don't write a traditional Javascript function. Instead, we tell JQuery to assign a click event to a particular DOM object ( id="checkAllAuto" ). In that event, we will then define and run a function.

$( id ).click()
$('#checkAllAuto').click(
   function()
   {
      $( "INPUT[type='checkbox']").attr('checked', $('#checkAllAuto').is(':checked'));   
   }
)

By not placing this code inside a defined function, we're defining the onclick event for the form element checkAllAuto when the page loads.

The line of JQuery inside the click event is broken down like this:

  1. $("INPUT[type='checkbox']"): Find all form elements of type "checkbox"
  2. .attr('checked', $('#checkAllAuto').is(':checked'));: and set their attribute checked to true or false
  3. $('#checkAllAuto').is(':checked'): based on the checked value of the form element checkAllAuto.

Wow! That's even less code. But there's a problem in that this code check or unchecks every checkbox in the form since we didn't specify a name attribute to find.

4. Merging options 2 and 3

Finally, we can merge the techniques used in the last two examples to check or uncheck multiple groups of checkboxes in the same form.

<p>4a. 
    <input type="checkbox" name="checkAllMyCB" id="checkAllMyCB" οnclick="jqCheckAll2( this.id, 'myCB' )"/> Check All named  "myCB" with JQuery onclick.
</p>
   
<p>4b. 
    <input type="checkbox" name="checkAllYourCB" id="checkAllYourCB" οnclick="jqCheckAll2( this.id, 'yourCB' )"/> Check All named  "yourCB" with JQuery onclick.
</p>

These two checkboxes will each mark a specific named group of checkboxes based on their own checked status.

jqCheckAll2()
function jqCheckAll2( id, name )
{
   $( "INPUT[@name=" + name +  "][type='checkbox']").attr('checked', $('#' + id).is(':checked'));
}

Broken down:

  1. $("INPUT[@name=" + name + "]: Find all INPUT elements whose name is the value of the name argument.
  2. [type='checkbox']"): and whose element type is checkbox
  3. .attr('checked', $('#' + id).is(':checked'));: and mark its checked attribute as true or false based on the checked status of the form element id.

5. I forgot your name (Added 7/16/2008)

You don't even have to use names or IDs on the checkboxes you want to check. All you need is the ID of their parent container. I've updated the FORM to add an ID to the two TDs that contain the groups of checkboxes.

<td id="left"> <!-- check boxes --> </td>
<td id="right"><!-- check boxes --> </td>

And two more checkboxes to trigger checking any checkboxes they contain:

<p>5a. 
    <input type="checkbox" id="checkL" οnclick="jqCheckAll3(this.id, 'left');"/> JQuery Check All Left Column 
</p>
<p>5b.
    <input type="checkbox" id="checkR" οnclick="jqCheckAll3(this.id, 'right');"/> JQuery Uncheck All Right Column
</p>

And the function they call:

jqCheckAll3()
function jqCheckAll3( id, pID )
{
   $(  "#" + pID +  " :checkbox").attr('checked', $('#' + id).is(':checked'));
}

Broken down:

  1. $( "#" + pID: Find the element with this ID (could be a DIV, SPAN, FIELDSET, etc.)
  2. + " :checkbox"): and for all elements of type "checkbox" inside that element,
  3. .attr('checked', $('#' + id).is(':checked'));: mark their checked attribute as true or false based on the checked status of the form element id.

re: #1, you could even get more specific by saying:

$( "TD#" + pID)

re: #2, I replaced [type='checkbox'] with " :checkbox" based on Richard's comment.

Summary

Hopefully, this simple (?!) example shows some of the power of the JQuery library. Give it a try when you start your next project or even better, see how you might incorporate it in an existing one. Once you get the basics down, you may find that you can get more done faster and with less code than you could by sticking to Old School Javascript.

References

The JQuery website
JQuery Google Group
DFW CFUG Google Group
JQuery Docs: Attributes/attr
JQuery Docs: Selectors/checked

 

 

aticle from:http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery

 

 

 

 

欢迎加群互相学习,共同进步。QQ群:iOS: 58099570 | Android: 572064792 | Nodejs:329118122 做人要厚道,转载请注明出处!






















本文转自张昺华-sky博客园博客,原文链接:http://www.cnblogs.com/sunshine-anycall/archive/2010/02/27/1674650.html ,如需转载请自行联系原作者


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值