`

Check All Checkboxes with JQuery[转]

    博客分类:
  • j2ee
阅读更多

jq(

function(){ jq('#checkAllAuto').click(

 

function()

{

jq(

"INPUT[type='checkbox']").attr('checked', jq('#checkAllAuto').is(':checked'));

}

);

});

参考文献
Posted At : July 9, 2008 10:16 PM | Posted By : Adrian J. Moreno
Related Categories: JQuery, Javascript

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.

 

myCB yourCB
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" onclick="checkAll(1);"/>
<input type="button" name="ca_v1_off" value="Uncheck All myCB" onclick="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" onclick="jqCheckAll('myForm', 'myCB', 1);"/>
<input type="button" name="ca_v2_off" value="JQuery Uncheck All myCB" onclick="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" onclick="jqCheckAll2( this.id, 'myCB' )"/> Check All named "myCB" with JQuery onclick.
</p>
   
<p>4b.
   <input type="checkbox" name="checkAllYourCB" id="checkAllYourCB" onclick="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" onclick="jqCheckAll3(this.id, 'left');"/> JQuery Check All Left Column
</p>
<p>5b.
   <input type="checkbox" id="checkR" onclick="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

 

 

分享到:
评论

相关推荐

    How to Check all Checkboxes Using Javascript.zip

    在JavaScript编程领域,"How to Check all Checkboxes Using Javascript.zip" 这个资源包主要聚焦于如何使用JavaScript一次性选中所有复选框(checkboxes)的功能。在网页交互设计中,这种功能常见于用户需要批量...

    checkboxes.js::check_box_with_check:一个jQuery插件,可让您更好地控制自己的复选框

    然后在jQuery之后添加jquery.checkboxes-###.min.js 。 产品特点 选中上下文中的所有复选框。 取消选中上下文中的所有复选框。 切换上下文中所有复选框的状态。 启用范围选择。 限制每个上下文中已选中复选框的...

    jquery操作asp.net中GridView方法

    用户可通过:http://www.jquerybyexample.net/2013/07/jquery-gridview-aspnet-tips-and-tricks.html 下载 Formatting Related Formatting ASP.NET ... Check/uncheck checkboxes in Asp.net GridView using jQuery

    js check复选

    在这个场景下,`js check all`标签暗示我们关注的是如何用JavaScript实现全选和全不选的功能。下面将详细介绍这一知识点,并结合提供的文件名`check_all_none.css`、`check_all_none.html`和`check_all_none.js`来...

    Hold-Shift-and-Check-Checkboxes

    要实现“Hold-Shift-and-Check-Checkboxes”功能,我们需要利用JavaScript(通常配合jQuery库,虽然纯JavaScript也可以实现)。当用户按下Shift键并点击复选框时,程序会检测到这一行为,并根据当前选中的复选框对...

    240多个jQuery UI插件

    - **jQuery Checkbox (checkboxes with images)**: 使用图片替代复选框。 - **jQuery Spin Button Control**: 实现数值增减控制。 - **jQuery Ajax Form Builder**: 快速构建Ajax表单。 - **jQuery Focus Fields...

    jquery、js操作checkbox全选反选.docx

    function checkAll() { $('input[name="TheID"]').prop("checked", true); } ``` - **解析**:使用jQuery的选择器`$('input[name="TheID"]')`来选择所有名为`TheID`的Checkbox,然后使用`prop()`方法设置它们的`...

    jquery 对checkbox的操作

    // select all checkboxes with class 'myCheckboxes' $(".myCheckboxes").prop("checked", false); // unselect all ``` 六、与其他元素关联 jQuery允许你根据checkbox的状态改变其他元素的属性。例如,当一个...

    240多个jQuery插件

    17. jQuery Checkbox (checkboxes with images):带图片的复选框。 18. jQuery SpinButton Control:数值旋钮控制。 19. jQuery Ajax Form Builder:构建异步表单。 20. jQuery Focus Fields:自动聚焦输入。 21. ...

    test_check_ctreectrl_TreeCtrl_TVS_CHECKBOXES_

    在标题 "test_check_ctreectrl_TreeCtrl_TVS_CHECKBOXES_" 中提到的 "TVS_CHECKBOXES" 是`CTreeCtrl`的一个样式,表示树形控件的每个节点可以包含复选框,用户可以通过这些复选框来选择或取消选择节点。 在描述中...

    jquery全选反选

    在JavaScript的库中,jQuery是一个广泛使用的框架,它极大地简化了DOM操作、事件处理和Ajax交互。在网页交互设计中,复选框是常见的元素,用于让用户选择一个或多个选项。"jquery全选反选"这个主题就是关于如何利用...

    Jquery dataTable显示指定列

    在本文中,我们将深入探讨如何使用Jquery dataTable插件来显示指定列,特别是在处理隐藏列的情况下。`Jquery dataTable` 是一个强大且功能丰富的JavaScript库,用于处理HTML表格,提供了排序、过滤、分页等特性,极...

    jquery-toggle-checkboxes:一个简单的jQuery插件,可以根据另一个复选框的更改状态来取消选中页面上所有已启用的复选框

    jQuery切换复选框一个简单的jQuery插件,它基于另一个复选框的更改状态来选中/取消选中页面上所有已启用的复选框。... $('#check-all').change(function() { $(this).toggleCheckboxes();}); 另外,

    纯CSS3炫酷checkbox美化库checkboxes.css

    同时,`related`目录可能包含了一些相关的资源链接,如`jQuery之家.url`,这可能是用于查找更多CSS3或前端开发资源的链接。 **四、注意事项** 1. 请确保浏览器支持CSS3特性,否则某些效果可能无法显示。 2. 考虑到...

    jquery插件表

    - **jQuery Checkbox (checkboxes with images)**:用图片替换复选框的默认样式。 - **jQuery SpinButton Control**:创建带有上下箭头的数字输入框。 - **jQuery Ajax Form Builder**:构建Ajax表单的工具。 - **...

    ListView控件使用CheckBoxes属性实现单选功能

    在某些应用场景中,我们需要让用户能够选择列表中的项目,而CheckBoxes属性就是为此设计的。本篇文章将详细介绍如何利用ListView控件的CheckBoxes属性来实现单选功能。 首先,我们需要创建一个WinForm应用程序,并...

    jquery Checkbox 全选 反选 全不选 多种实现方法

    在网页开发中,jQuery 是一个广泛使用的 JavaScript 库,它简化了 DOM 操作、事件处理以及Ajax交互等任务。在涉及到表单元素如复选框(Checkbox)时,经常需要实现全选、反选和全不选的功能。下面将详细探讨 jQuery ...

    jQuery插件教程(搜罗了全部插件).pdf

    6. 其他实用插件:如jQuery Masked Input用于输入格式限制,TypeWatch Plugin用于检测输入框内容变化,jTagging用于标签输入,jQuery Checkbox (checkboxes with images)用于自定义样式的复选框等,这些插件丰富了...

    有关全选、反选、取消 的jquery效果

    至于压缩包中的`check`文件,由于没有具体的内容,我们无法提供更多的细节。不过根据上下文,这可能是一个示例代码文件,包含了实现全选、反选和取消选择功能的jQuery代码。 总的来说,理解并应用这些jQuery方法...

Global site tag (gtag.js) - Google Analytics