我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
对于jQuery 1.6+
$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
对于jQuery 1.5.x及以下版本
$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);
为了检查,
$('.myCheckbox').removeAttr('checked');
其他回答
你可以的
$('.myCheckbox').attr('checked',true) //Standards compliant
or
$("form #mycheckbox").attr('checked', true)
如果在onclick事件中有要激发的复选框的自定义代码,请改用此代码:
$("#mycheckbox").click();
可以通过完全删除该属性来取消选中:
$('.myCheckbox').removeAttr('checked')
您可以这样选中所有复选框:
$(".myCheckbox").each(function(){
$("#mycheckbox").click()
});
我无法通过以下方式实现:
$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');
true和false都会选中该复选框。对我有用的是:
$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', ''); // For unchecking
如果您碰巧在使用Bootstrap(可能是无意中)。。。
$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')
http://www.bootstraptoggle.com/
这可能会帮助某人。
HTML5
<input id="check_box" type="checkbox" onclick="handleOnClick()">
JavaScript。
function handleOnClick(){
if($("#check_box").prop('checked'))
{
console.log("current state: checked");
}
else
{
console.log("current state: unchecked");
}
}
您还可以使用新方法扩展$.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()。