导航首页 » 技术教程 » jQuery实现CheckBox全选、全不选功能
jQuery实现CheckBox全选、全不选功能 108 2024-02-05   

废话不多说了,直接给大家贴代码了,具体代码如下所示:

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="utf-8" /> 
<title>jQuery实现CheckBox全选、全不选</title> 
<script src="http://code.jquery.com/jquery-2.2.3.min.js" type="text/javascript"></script>   
<script type="text/javascript"> 
    $(function() { 
    $(':checkbox').click(function(evt){ 
      // 阻止冒泡 
      evt.stopPropagation(); 
    }); 
      //判断是否全选 
      $("#checkAll").click(function() { 
        $('input[name="subBox"]').prop("checked",this.checked);  
      }); 
      var $subBox = $("input[name='subBox']"); 
      $subBox.click(function(){ 
        //alert($subBox.length); 
        //alert($("input['subBox']:checked").length); 
        $("#checkAll").prop("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false); 
      }); 
      //用于检查是否选中,选中的话提示值 
      $("#butt").click(function (){ 
        //$('input[name="subBox"]').prop("checked",this.checked);  
        var arrChk=$("input[name='subBox']:checked"); 
        $(arrChk).each(function(){  //each() 遍历函数 
          alert(this.value);             
        });  
        if(arrChk.length==0){ 
          alert("没有选中") 
        } 
      }); 
    }); 
  </script> 
</head> 
<body> 
  <div> 
    <input id="checkAll" type="checkbox" />全选 
    <input name="subBox" type="checkbox" value="1" />选项1 
    <input name="subBox" type="checkbox" value="2"/>选项2 
    <input name="subBox" type="checkbox" value="3"/>选项3 
    <input name="subBox" type="checkbox" value="4"/>选项4 
    <input type="button" id="butt" value="检查是否选中"/> 
  </div> 
</body> 
</html> 

jQuery版本问题

原本操作属性用的是 $("XXX").attr("attrName");

而jQuery的版本用的是2.1.1,这就是存在一个兼容性和稳定性问题。

jQuery API明确说明,1.6+的jQuery要用prop,尤其是checkBox的checked的属性的判断,

即 使用代码如下:

$("input[name='checkbox']").prop("checked"); 
$("input[name='checkbox']").prop("disabled", false); 
$("input[name='checkbox']").prop("checked", true);

于是乎将attr改为prop,问题得解。

相关阅读:

jQuery操作复选框(CheckBox)的取值赋值实现代码

jQuery对checkbox 复选框的全选全不选反选的操作

Jquery EasyUI实现treegrid上显示checkbox并取选定值的方法

以上所述是小编给大家介绍的jQuery实现CheckBox全选、全不选功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对绿夏网网站的支持!



!!!站长长期在线接!!!

网站、小程序:定制开发/二次开发/仿制开发等

各种疑难杂症解决/定制接口/定制采集等

站长微信:lxwl520520

站长QQ:1737366103