jquery判断和操作checkbox的各种问题方法

2017年08月31日 10:54:51益点益滴4165

使用jQuery对checkbox类型的input进行操作是一个难点和重点,很多前端新手对其了解不是很透彻。时间久了不用,很多资深前端在实践中有时也难免对某些操作模棱两可,记不清楚,那么今天小编就对其做一些简单的总结,希望能帮到大家。

首先我们来看jquery对checkbox赋值checked选中的几种方法:

$("#cb1").attr("checked","checked");
$("#cb1").attr("checked",true);

所有的jquery版本都可以这样赋值。对checkbox是否选中进行checked判断,不同jquery版本存在差异:

.attr('checked):   //版本1.6+返回:”checked”或”undefined” ;1.5-返回:true或false
.prop('checked'): //16+:true/false
.is(':checked'):    //所有版本:true/false//不能忘记冒号

其中.prop是jquery1.6+版本以后新增的操作函数,用该功能赋值时可以这样写:

$("#cb1″).prop("checked","checked");//与attr一样
$("#cb1″).prop("checked",true);//与attr一样
$("#cb1″).prop({checked:true}); //map键值对
$("#cb1″).prop("checked",function(){
    return true;//函数返回true或false
});

下面我们来看一个批量处理多个checkbox的全选和取消全选的代码实例:

<input id="checkAll" type="checkbox" />全选
<input name="subBox" type="checkbox" />项1
<input name="subBox" type="checkbox" />项2
<input name="subBox" type="checkbox" />项3
<input name="subBox" type="checkbox" />项4
<script src="http://apps.bdimg.com/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
        $(function() {
           $("#checkAll").click(function() {
                $('input[name="subBox"]').attr("checked",this.checked); 
            });
            var $subBox = $("input[name='subBox']");
            $subBox.click(function(){
                $("#checkAll").attr("checked",$subBox.length == $("input[name='subBox']:checked").length ? true : false);
            });
        });
    </script>

最后我们再附上一些checkbox checked属性常用操作代码和说明,另外,checkbox以及radio的disabled属性操作也是大同小异,可以参考:

var val = $("#checkAll").val();// 获取指定id的复选框的值  

var isSelected = $("#checkAll").attr("checked"); // 判断id=checkAll的那个复选框是否处于选中状态,选中则isSelected=true;否则isSelected=false;  //jquery1.6之后版本,用prop()判断。应该写成 isSelected = $("#checkAll").prop("checked");

$("#checkAll").attr("checked", true);// or  

$("#checkAll").attr("checked", 'checked');// 将id=checkbox_id3的那个复选框选中,即打勾  

$("#checkAll").attr("checked", false);// or  

$("#checkAll").attr("checked", '');// 将id=checkbox_id3的那个复选框不选中,即不打勾  

$("input[name=subBox][value=3]").attr("checked", 'checked');// 将name=subBox, value=3 的那个复选框选中,即打勾  

$("input[name=subBox][value=3]").attr("checked", '');// 将name=subBox, value=3 的那个复选框不选中,即不打勾  

$("input[type=checkbox][name=subBox]").get(2).checked = true;// 设置index = 2,即第三项为选中状态  

$("input[type=checkbox]:checked").each(function(){ //由于复选框一般选中的是多个,所以可以循环输出选中的值  

    alert($(this).val());  

}); 

//jquery1.6之后新增.prop()属性,因此jquery1.6之后的版本,可以用var isSelected = $("#checkAll").prop("checked");选中则isSelected=true;否则isSelected=false;  来判断是否选中

超赞,真给力!嗯,必须鼓励~

打赏4
账号:mxy310@163.com[复制]
账号:77940140[复制]