samedi 21 novembre 2015

Master switchery control all child switchery

I'm trying to create One Master switchery checkbox which controls all the child switchery checkboxes state

Code is

$(function() {
    // Initialize multiple switches
    if (Array.prototype.forEach) {
        var elems = Array.prototype.slice.call(document.querySelectorAll('.switches'));
        elems.forEach(function(html) {
            var switcherys = new Switchery(html);
        });
    }
    else {
        var elems = document.querySelectorAll('.switches');
        for (var i = 0; i < elems.length; i++) {
            var switcherys = new Switchery(elems[i]);
        }
    }
});
//Master Switch 
var MasterCheckbox = document.querySelector('.special');
//Master Switch Change State Check
MasterCheckbox.onchange = function () {
    if (MasterCheckbox.checked) {
        //Change all child switchery checkboxes state
        var special = document.querySelector('.chkChange');
        // $(special).attr("checked", true);
        special.checked = true;
        if (typeof Event === 'function' || !document.fireEvent) {
            var event = document.createEvent('HTMLEvents');
            event.initEvent('change', true, true);
            special.dispatchEvent(event);
        } else {
            special.fireEvent('onchange');
        }
    } else {
        var special = document.querySelector('.chkChange');
        //$(special).attr("checked", false);
        special.checked = false;
        if (typeof Event === 'function' || !document.fireEvent) {
            var event = document.createEvent('HTMLEvents');
            event.initEvent('change', true, true);
            special.dispatchEvent(event);
        } else {
            special.fireEvent('onchange');
        }
    }

};
<link rel="stylesheet" href="http://ift.tt/1SRb9g6" />
<script src="http://ift.tt/1q8wkLp"></script>
<script src="http://ift.tt/1lBDMUi"></script>
<table>
    <tr>
        <td>Master Switch</td>
        <td>
            <input type="checkbox" class="switches special" />
        </td>
    </tr>
    <tr>
        <td>Child Switch</td>
        <td>
            <input type="checkbox" class="switches chkChange" />
        </td>
    </tr>
    <tr>
        <td>Child Switch</td>
        <td>
            <input type="checkbox" class="switches chkChange" />
        </td>
    </tr>
    <tr>
        <td>Child Switch</td>
        <td>
            <input type="checkbox" class="switches chkChange" />
        </td>
    </tr>
</table>
  1. One Master switchery check box to control all child switchery checkboxes state
  2. If one child switchery checkbox state enable master switchery checkbox state change to enable if disabled otherwise remain disable

Problem is that not able to change state of all child switchery checkboxes but only one, can check the code snippet

Plugin Site

Github

Working Fiddle Example




Aucun commentaire:

Enregistrer un commentaire