简体   繁体   中英

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?

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. You should compare defaultChecked and checked properties.

$isModified = $this.find('input')[0].defaultChecked !== $this.find('input')[0].checked;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM