[英]How to determine if checkbox is different from its initial checked state
I know I can use defaultChecked
to determine if what the initial state of checkbox is, but how can I determine if one of these has changed from the default?我知道我可以使用defaultChecked
来确定复选框的初始状态是否是什么,但是如何确定其中一个是否已从默认值更改?
I need to set a variable so I can manipulate something else based on the result of this, this is what I currently have:我需要设置一个变量,以便我可以根据这个结果操作其他东西,这就是我目前拥有的:
// This checks if a checkbox has changed from being initially checked
$isModified = $(this).find('input')[0].defaultChecked !== $(this).find('input').prop('checked') ? true : false
[EDIT] I need to check if a checkbox has changed from it's default state regardless of whether it was checked initially or not. [编辑] 无论最初是否选中复选框,我都需要检查复选框是否已从其默认状态更改。
This is what I thought might work (but doesn't):这就是我认为可能起作用的(但不起作用):
$isModified = $this.find('input')[0].defaultChecked !== $this.find('input')[0].defaultChecked ? true : false
Does anyone have a solution?有没有人有办法解决吗?
Thanks谢谢
[EDIT] After a lot of very helpful.. help. [编辑] 经过很多非常有帮助的..帮助。 Here is my solution that is fired when there is a change event on one of the inputs:这是我的解决方案,当输入之一发生更改事件时会触发该解决方案:
$('#input-parent').each(function(i) {
var $this = $(this),
isModified
;
$this.find('input').each(function() {
var $this = $(this);
if ( !isModified) {
isModified = $this[0].defaultChecked !== $this[0].checked;
}
});
if ( isModified ) {
// Do something
} else {
// Do something else
}
});
in your example you are comparing defaultChecked
to defaultChecked
property.在您的示例中,您将defaultChecked
与defaultChecked
属性进行比较。 You should compare defaultChecked
and checked
properties.您应该比较defaultChecked
和已checked
属性。
$isModified = $this.find('input')[0].defaultChecked !== $this.find('input')[0].checked;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.