griegs griegs - 21 days ago 7
jQuery Question

Select on two attributes being different

I'd like to be able to select checkboxes where the checked value is not equal to an attribute value.

So I may have

<input type="checkbox" originalValue="false" checked="checked">

or
<input type="checkbox" originalValue="true">
so now the user unchecked it and so it is different.

I may have a few thousand of these on a page so I just want the ones that the user has changed from their original value. So originally the checkbox was checked, then they deselected it.

Or if it was checked, then they unchecked it, and then checked it again, then I don't want that checkbox.

Is there an elegant jQuery way to do this?

Answer

There's always an elegant way to do things - use filter and filter out the opposites:

var changedElements = $("input:checkbox").filter(function() {
    var originalValue = $(this).attr("originalValue"); //unsure if this is auto-parsed to a bool, will have to check
    var originalBoolValue = originalValue === "true";

    return originalBoolValue != this.checked;
});