我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
如果您碰巧在使用Bootstrap(可能是无意中)。。。
$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')
http://www.bootstraptoggle.com/
其他回答
您还可以使用新方法扩展$.fn对象:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
然后你可以这样做:
$(":checkbox").check();
$(":checkbox").uncheck();
或者,如果您使用其他使用这些名称的库,您可能希望为它们提供更多的唯一名称,如mycheck()和myuncheck()。
假设问题是。。。
如何选中按值设置的复选框?
请记住,在典型的复选框集中,所有输入标记都具有相同的名称,它们的不同之处在于属性值:集合中的每个输入都没有ID。
Xian的答案可以用更具体的选择器扩展,使用以下代码行:
$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
如果您考虑使用vanilla js而不是jquery,那么有一个解决方案:
//for one element:
document.querySelector('.myCheckBox').checked = true /* or false */ //will select the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
checkbox.checked = true //or false
}
您可以使用JavaScript以不同的方式检查复选框检查条件。你可以在下面看到。
第一种方法-$('.myCheckbox').prop('checked',true);第二种方法-$('.myCheckbox').attr('checked',true);第三种方法(如果选中或未选中复选框,则用于检查条件)-$('.myCheckbox').is(':checked')
这是完整的答案使用jQuery
我测试了它,它100%工作:D
// when the button (select_unit_button) is clicked it returns all the checed checkboxes values
$("#select_unit_button").on("click", function(e){
var arr = [];
$(':checkbox:checked').each(function(i){
arr[i] = $(this).val(); // u can get id or anything else
});
//console.log(arr); // u can test it using this in google chrome
});