我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
$(".myCheckBox").prop("checked","checked");
其他回答
正如@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();
这可能是最短、最简单的解决方案:
$(".myCheckBox")[0].checked = true;
or
$(".myCheckBox")[0].checked = false;
更短的是:
$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;
这里还有一个jsFiddle。
试试看:
$('#checkboxid').get(0).checked = true; //For checking
$('#checkboxid').get(0).checked = false; //For unchecking
如果您正在使用PhoneGap进行应用程序开发,并且您想立即显示按钮上的值,请记住执行此操作
$('span.ui-[controlname]',$('[id]')).text("the value");
我发现,如果没有跨度,无论你做什么,界面都不会更新。
下面是用按钮选中和取消选中的代码:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
});
set=unset;
});
});
更新:这里是使用更新的Jquery 1.6+prop方法的相同代码块,它替换了attr:
var set=1;
var unset=0;
jQuery( function() {
$( '.checkAll' ).live('click', function() {
$( '.cb-element' ).each(function () {
if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
});
set=unset;
});
});