jQuery操作复选框checkbox方法

jQuery操作复选框checkbox方法

$("#id1").attr('checked') // 返回:"checked"或"undefined";
$("#id1").prop('checked') // 返回true/false
$("#id1").is(':checked')  // 返回true/false

jQuery赋值checked的几种写法: 所有的jQuery版本都可以这样赋值,不建议用attr();

$("#id1").attr("checked","checked"); //通用做法,现在不推荐
$("#id1").attr("checked",true); //不标准,不推荐
$("#id1").attr("checked","true"); //不标准,不推荐

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

获取单个checkbox选中项的值(三种写法)

$("#id1").find("input:checkbox:checked").val()
//或者
$("#id1").find("input:[type='checkbox']:checked").val();
$("#id1").find("input[type='checkbox']:checked").val();
//或者
$("#id1").find("input:[name='ck']:checked").val();
$("#id1").find("input[name='ck']:checked").val();

获取多个checkbox选中项

$("#id").find('input:checkbox').each(function() { //遍历所有复选框
    if ($(this).prop('checked') == true) {
        console.log($(this).val()); //打印当前选中的复选框的值
    }
});

function getCheckBoxVal(){ //jquery获取所有选中的复选框的值
    var chk_value =[];
    $("#id").find('input[name="test"]:checked').each(function(){ //遍历,将所有选中的值放到数组中
        chk_value.push($(this).val());
    });
    alert(chk_value.length==0 ? '你还没有选择任何内容' :chk_value);
}

设置第一个checkbox 为选中值

$("#id").find('input:checkbox:first').prop("checked",true);
//或者
$("#id").find('input:checkbox').eq(0).prop("checked",true);

设置最后一个checkbox为选中值

$("#chk1").find('input:checkbox:last').prop("checked",true);

出处:https://www.cnblogs.com/gzb1/p/16289116.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值