我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
要使用jQuery 1.6或更高版本选中复选框,只需执行以下操作:
checkbox.prop('checked', true);
要取消选中,请使用:
checkbox.prop('checked', false);
下面是我喜欢使用jQuery切换复选框的内容:
checkbox.prop('checked', !checkbox.prop('checked'));
如果使用jQuery 1.5或更低版本:
checkbox.attr('checked', true);
要取消选中,请使用:
checkbox.attr('checked', false);
其他回答
正如@livefree75所说:
jQuery 1.5.x及以下版本
您还可以使用新方法扩展$.fn对象:
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").attr("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").removeAttr("checked");
}
});
}(jQuery));
但是在jQuery的新版本中,我们必须使用如下内容:
jQuery 1.6+
(function($) {
$.fn.extend({
check : function() {
return this.filter(":radio, :checkbox").prop("checked", true);
},
uncheck : function() {
return this.filter(":radio, :checkbox").prop("checked",false);
}
});
}(jQuery));
然后你可以这样做:
$(":checkbox").check();
$(":checkbox").uncheck();
试试看:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
您还可以使用新方法扩展$.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()。
如果您考虑使用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
}
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();
最后一个将激发复选框的单击事件,其他的则不会。因此,如果您在onclick事件中为要激发的复选框设置了自定义代码,请使用最后一个。