我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
我想这样做,使用jQuery勾选复选框:
$(".myCheckBox").checked(true);
or
$(".myCheckBox").selected(true);
这样的事情存在吗?
当前回答
如果您考虑使用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
}
其他回答
我错过了解决方案。我将始终使用:
if ($('#myCheckBox:checked').val() !== undefined)
{
//Checked
}
else
{
//Not checked
}
这可能会帮助某人。
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");
}
}
if($('jquery_selector').is(“:checked”)){//某些代码}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script>
这里有一种不使用jQuery的方法
函数addOrAttachListener(el,type,listener,useCapture){if(el.addEventListener){el.addEventListener(类型,监听器,useCapture);}否则如果(el.attachEvent){el.attachEvent(“on”+类型,监听器);}};addOrAttachListener(窗口,“加载”,函数(){var cbElem=文档.getElementById(“cb”);var rcbElem=文档.getElementById(“rcb”);addOrAttachListener(cbElem,“单击”,函数(){rcbElem.checked=cbElem.check;},假);},假);<label>单击我!<input id=“cb”type=“checkbox”/></label><label>反射:<input id=“rcb”type=“checkbox”/></label>
正如@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();