原创

checkbox选中和取消选中使用

input checkbox复选框想要实现选中和取消选中,先了解一下checked属性的用法

一、input标签的checked属性的定义
1、checked 属性是一个布尔属性。
2、checked 属性规定在页面加载时应该被预先选定的 <input> 元素。
3、checked 属性适用于 <input type="checkbox"> 和 <input type="radio">。
4、checked 属性也可以在页面加载后,通过 JavaScript 代码进行设置。

二、input标签的checked属性的用法
1、jQuery赋值checked
$("#inputId").attr("checked","checked"); //通用做法,现在不推荐了
$("#inputId").attr("checked",true); //不标准,不推荐了
$("#inputId").attr("checked","true"); //不标准,不推荐了

2、jQuery判断checked是否是选中状态
$("#inputId").attr('checked'); // 返回:"checked"或"undefined" ;
$("#inputId").prop('checked');  // 返回true/false
$("#inputId").is(':checked'); // 返回true/false //别忘记冒号哦

3、jQuery的prop()的赋值
$("#inputId").prop("checked",true); //标准写法,推荐!
$("#inputId").prop({checked:true}); //map键值对
$("#inputId").prop("checked",function(){ return true;//函数返回true或false });
$("#inputId").prop("checked","checked"); //不标准

三、jQuery对checkbox使用实例
1、全部选中或全部取消选中

$("#inputId").find('input:checkbox').each(function() { 
    $(this).prop('checked', true); 
});

//或者

$("#inputId").find('input:checkbox').each(function () {
    $(this).prop('checked',false);
});


2、选中所有奇数项或偶数项
$("#inputId").find("input[type='checkbox']:even").prop("checked",true); //选中所有偶数
$("#inputId").find("input[type='checkbox']:odd").prop("checked",true); //选中所有奇数

3、checkbox反选操作

$("#buttonId").click(function(){
    $("input[type='checkbox']").each(function(){ //反选
    if($(this).prop("checked")){
        $(this).prop("checked",false);
    } else{
        $(this).prop("checked",true);
    }
    });
});

或者

$("#buttonId").on('click',function(){
    //反选所有的复选框(没选中的改为选中,选中的改为取消选中)
    $("#inputId").find("input[type='checkbox']").prop("checked", 
    function(index, oldValue){
        return !oldValue;
    });
}

4、设置默认选中的值
$("#inputId").find('input:checkbox').eq(索引值).prop('checked', true);

本文链接地址:http://www.ysxbohui.com/article/164

正文到此结束