jQuery全选与取消全选实现代码

发表于 2017-02-12 3210 次查看
基于jquery的全选和取消全选 只用一个checkbox来实现,更加直观一些了,并且能在IE和FF下都兼容。

引用Jquery 库jquery-1.4.1-vsdoc.js 等


jQuery.attr  获取/设置对象的属性值,如:

 代码如下 复制代码

$("input[name='chk_list']").attr("checked");     //读取所有name为'chk_list'对象的状态(是否选中)

$("input[name='chk_list']").attr("checked",true);      //设置所有name为'chk_list'对象的checked为true

再如:

 代码如下 复制代码

$("#img_1").attr("src","test.jpg");    //设置ID为img_1的<img>src的值为'test.jpg'
$("#img_1").attr("src");     //读取ID为img_1的<img>src值

  下面的代码是获取上面实例中选中的checkbox的value值:


Jquery脚本代码——————————————————————

 代码如下 复制代码

$(function() {
$('#inputCheck').click(function() {
$("input[name='Checkbox1']").attr("checked", $(this).attr("checked"));
});
}); // 全选

$(function() {
$("#select_reverse").click(function() {
$("input[name='Checkbox1']").each(function(idx, item) {
$(item).attr("checked", !$(item).attr("checked"));
})
});
});//反选

html 前台代码————————————————————————

 代码如下 复制代码
[code]
<input id="inputCheck" type="checkbox" />全选
<input id="select_reverse" type="checkbox" />反选
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
<input name="Checkbox1" type="checkbox" />
[html]

实例

 代码如下 复制代码

<input type="checkbox" name="test[]" />选项1
<input type="checkbox" name="test[]" />选项2
<input type="checkbox" name="test[]" />选项3
<input type="checkbox" name="test[]" />选项4
<input type="checkbox" name="test[]" />选项5
<input type="checkbox" id="checkall" />全选

JQuery代码

 代码如下 复制代码


;(function($){
 $.fn.checkall = function(options){
  var defaults = {chname:"checkname[]", callback:function(){}},
   options = $.extend(defaults, options),
   $obj = $(this),
   $items = $("input[name='"+options.chname+"']"),
   checkedItem = 0;
  $items.click(function(){
   if($items.filter(":checked").length === $items.length){
    $obj.attr("checked",true);
   }else{
    $obj.removeAttr("checked");
   }
   checkedItem = $items.filter(":checked").length;
   if(typeof options.callback === 'function') options.callback(checkedItem);
  });
  return $obj.each(function(){
   $(this).click(function(){
    if($(this).attr('checked')){
     $items.attr("checked",true);
    }else{
     $items.removeAttr("checked");
    }
    checkedItem = $items.filter(":checked").length;
    if(typeof options.callback === 'function') options.callback(checkedItem);
   });
  });
 }
})(jQuery);

调用方法

 代码如下 复制代码

$(function(){
 $("#checkall").checkall({chname:"test[]", callback: function(e){alert(e)}});
})

发表回复
你还没有登录,请先登录注册
话题作者
头衔:
活跃成员

课程推荐

推荐资讯