[英]Toggling checkbox only checks, doesn't uncheck
I am trying to toggle some checkboxes using jQuery and I am using code that is recommended often when searching for toggling checkboxes, but it only seems to check them instead of toggling. 我正在尝试使用jQuery切换某些复选框,而我正在使用在搜索切换复选框时经常建议使用的代码,但似乎只检查它们而不是进行切换。
Here's a jsfiddle for it: 这是一个jsfiddle:
http://jsfiddle.net/wgHpG/ http://jsfiddle.net/wgHpG/
The HTML: HTML:
<button id="priority-categories" class="btn">Priority</button>
<input type="checkbox" name="category" value="1" id="1">
<input type="checkbox" name="category" value="2" id="2">
<input type="checkbox" name="category" value="3" id="3">
The js: js:
$('#priority-categories').click(function(){
var categories = [1, 3];
$.each(categories, function(key, value) {
$('#' + value).prop('checked', !$('#' + value).checked);
});
});
.checked
is not a property of the jquery object representing the checkbox element. .checked
不是表示复选框元素的jquery对象的属性。
Use .is(':checked')
instead 使用
.is(':checked')
代替
jQuery objects don't have a .checked
property, only DOM elements have it. jQuery对象没有
.checked
属性,只有DOM元素具有。
$('#' + value).checked
will always be undefined
, and hence !$(..).checked
will always be true
. $('#' + value).checked
将始终是undefined
,因此!$(..).checked
将始终为true
。
You can pass a callback to .prop
: 您可以将回调传递给
.prop
:
$('#' + value).prop('checked', function(i, checked) {
return !checked;
});
Note that IDs starting with numbers are not valid in HTML4. 请注意,以数字开头的ID在HTML4中无效。
jQuery elements don't have a 'checked' property. jQuery元素没有'checked'属性。 You need to either use a jQuery method to check if it is checked or convert it back into a DOM element
您需要使用jQuery方法来检查是否已选中,或者将其转换回DOM元素
!$('#' + value)[0].checked
or 要么
!$('#' + value).prop('checked')
改成
$('#' + value).prop('checked', !$('#' + value).is(":checked"));
$('#' + value).prop('checked', !$('#' + value).attr("checked"))
This code, while a little verbose, will toggle as you expect - http://jsfiddle.net/wgHpG/2/ 该代码虽然有些冗长,但将按您期望的那样切换-http: //jsfiddle.net/wgHpG/2/
$('#priority-categories').click(function(){
var categories = [1, 3];
$.each(categories, function(key, value) {
if($('#'+value).is(':checked')) {
$('#' + value).prop('checked', false);
} else {
$('#' + value).prop('checked', true);
}
});
});
A slightly different approach might be to use jQuery to select the nodes then just toggle on the native DOM checkbox: 稍有不同的方法可能是使用jQuery选择节点,然后仅选中本机DOM复选框:
var categories = [1, 3];
$('#' + categories.join(',#')).each(function() {
this.checked = !this.checked;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.