1、获取单个已选择的checkbox选中项的value
$("input:checkbox:checked").val() ;
或
$("input:[type='checkbox']:checked").val();
或
$("input:[name='coupon_id']:checked").val();
2、获取多个checkbox选中项:
var arr
=[];
$('input:checkbox').each(function() {
if ($(this).is(':checked')) {
arr
.push($(this).val())
}
});
3、设置checkbox 选中值
checked或者true 代表选中;false未选中
(3.1)单个选中
$('input:checkbox:first').attr("checked",'checked');
或
$('input:checkbox').eq(n
).attr("checked",'true');
或
$('input:radio:last').attr('checked', 'checked');
或
$("input:checkbox[value='1']").attr('checked','true');
(3.2) 选中多个checkbox:
$('input:radio').slice(0,2).attr('checked','true');
或
$("input[type='checkbox']").prop("checked", true);
或
$('input:checkbox').each(function() {
$(this).attr('checked', true);
});
4、取消选中 (4.1)取消单个选中
$("input:checkbox[value='1']").prop("checked", false);
或
$("input:checkbox").eq(n
).prop("checked", false);
(4.2)全部取消
$("input[type='checkbox']").prop("checked", false);
或
$('input:checkbox').each(function () {
$(this).attr('checked',false);
});
番外:
<div class="checkbox_box">
<input type="checkbox" name="coupon_id" id="" value="1" class="checkbox_coupon" /><label for="">111
</label>
<input type="checkbox" name="coupon_id" id="" value="2" class="checkbox_coupon" /><label for="">222
</label>
<input type="checkbox" name="coupon_id" id="" value="3" class="checkbox_coupon" /><label for="">333
</label>
</div>
<p><input type="checkbox" name="coupon_id" id="all" value="" /><label for="all">全选
</label></p>
$("#all").on("click", function() {
if ($(this).is(':checked')) {
$("input[type='checkbox']").prop("checked", true);
} else {
$("input[type='checkbox']").prop("checked", false);
}
});
$(document
).on("change", '.checkbox_coupon', function() {
var selected_arr
= [];
var select_arr
= [];
var selected_len
= "";
var select_len
= "";
$(".checkbox_box").find("[name='coupon_id']:checked").each(function() {
selected_arr
.push($(this).val());
});
if (selected_arr
) {
selected_len
= selected_arr
.length
}
$(".checkbox_box").find("[name='coupon_id']").each(function() {
select_arr
.push($(this).val());
});
if (select_arr
) {
select_len
= select_arr
.length
}
if (select_len
== selected_len
) {
$('input:checkbox:last').attr("checked", true);
} else {
$('input:checkbox:last').attr("checked", false);
}
})
转载请注明原文地址:https://ipadbbs.8miu.com/read-12256.html