我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
如jQuery文档所述,请注意Internet Explorer 9之前的Internet Explorer内存泄漏:
在版本9之前的Internet Explorer中,使用.prop()设置DOM元素属性设置为除简单基元值以外的任何值如果属性为在移除DOM元素之前未移除(使用.removeProp())从文档中删除。在没有内存的情况下安全地设置DOM对象的值泄漏,请使用.data()。
其他回答
这是用jQuery检查和取消检查复选框的正确方法,因为它是跨平台标准的,并且允许表单转发。
$('.myCheckBox').each(function(){ this.checked = true; });
$('.myCheckBox').each(function(){ this.checked = false; });
通过这样做,您将使用JavaScript标准来检查和取消选中复选框,因此任何正确实现checkbox元素的“checked”属性的浏览器都将完美地运行此代码。这应该是所有主要的浏览器,但我无法在Internet Explorer 9之前进行测试。
问题(jQuery 1.6):
一旦用户单击复选框,该复选框将停止响应“选中”的属性更改。
下面是一个复选框属性在有人单击复选框后无法完成任务的示例(这在Chrome中发生)。
不停摆弄
解决方案:
通过在DOM元素上使用JavaScript的“checked”属性,我们能够直接解决问题,而不是试图操纵DOM来完成我们希望它做的事情。
不停摆弄
该插件将更改jQuery选择的任何元素的checked属性,并在所有情况下成功选中和取消选中复选框。因此,虽然这看起来像是一个负担过重的解决方案,但它将使您的网站的用户体验更好,并有助于防止用户受挫。
(function( $ ) {
$.fn.checked = function(value) {
if(value === true || value === false) {
// Set the value of the checkbox
$(this).each(function(){ this.checked = value; });
}
else if(value === undefined || value === 'toggle') {
// Toggle the checkbox
$(this).each(function(){ this.checked = !this.checked; });
}
return this;
};
})( jQuery );
或者,如果您不想使用插件,可以使用以下代码片段:
// Check
$(':checkbox').prop('checked', true);
// Un-check
$(':checkbox').prop('checked', false);
// Toggle
$(':checkbox').prop('checked', function (i, value) {
return !value;
});
试试看:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
在jQuery中,
if($("#checkboxId").is(':checked')){
alert("Checked");
}
or
if($("#checkboxId").attr('checked')==true){
alert("Checked");
}
在JavaScript中,
if (document.getElementById("checkboxID").checked){
alert("Checked");
}
如果您碰巧在使用Bootstrap(可能是无意中)。。。
$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')
http://www.bootstraptoggle.com/
这是完整的答案使用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
});