23 March 2016

Detecting change in state of a group of checkbox elements

Here’s how you can detect the original state of some checkboxes (or radio buttons). So to be clear, it will report if the state has changed and if the state has reverted back to its original state combination. It can be modified for all kinds of input elements and is handy, for example, when you want to offer a user a save option when a change is made to their original configuration.

Fiddle: https://jsfiddle.net/n2fole00/z40bm13g/

<head><script src="https://code.jquery.com/jquery-2.2.0.min.js"></script></head>

<input type="checkbox" name="id_1" id="id_1" value="id_1" checked="checked" />One
<input type="checkbox" name="id_2" id="id_2" value="id_2" />Two
<input type="checkbox" name="id_3" id="id_3" value="id_3" checked="checked" />Three

<br>Same state?: <span id="show">true</span>


// initial state object 
var initial = $(':checkbox').map(function(){ 
    return this.checked 

// detect clicks to checkboxs, radiogroups...
$( ':checkbox' ).click(function() {
    // assign user input to a comparing object 
    var change = $(':checkbox').map(function(){ 
        return this.checked 
    // compare the Objects and output the result
        JSON.stringify(initial) === JSON.stringify(change)


No comments:

Post a Comment