我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
这是完整的答案使用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
});
其他回答
这是用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;
});
假设问题是。。。
如何选中按值设置的复选框?
请记住,在典型的复选框集中,所有输入标记都具有相同的名称,它们的不同之处在于属性值:集合中的每个输入都没有ID。
Xian的答案可以用更具体的选择器扩展,使用以下代码行:
$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
$('controlCheckBox').click(function(){
var temp = $(this).prop('checked');
$('controlledCheckBoxes').prop('checked', temp);
});
如jQuery文档所述,请注意Internet Explorer 9之前的Internet Explorer内存泄漏:
在版本9之前的Internet Explorer中,使用.prop()设置DOM元素属性设置为除简单基元值以外的任何值如果属性为在移除DOM元素之前未移除(使用.removeProp())从文档中删除。在没有内存的情况下安全地设置DOM对象的值泄漏,请使用.data()。
正如@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();