i struggle to disable the Switchery checkbox but it creates me another Switchery checkbox on page . i first define the checkbox which is working great:
<div class="form-group">
<label class="col-md-2">
Additional Options
</label>
<div class="col-md-3">
<div class="">
<label>
<input type="checkbox" id="foo1"
name="foo1" class="js-switch"/>
</label>
</div>
</div>
</div>
now after the page loaded, i dynamically want to disable the checkbox so I do :
var foo1= document.getElementById('foo1')
var switchery = new Switchery(foo1);
switchery.disable();
it disable the checkbox BUT it creates me new checkbox near the one i defined already i don't understand why
I was using a template and it had this in their JS code:
$(document).ready(function () {
if ($(".js-switch")[0]) {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
var switchery = new Switchery(html, {
color: '#26B99A'
});
});
}
});
This runs when the page loads and may explain why you are seeing 2 switchery objects. You may have something initializing it in a JS script and then doing it again on the page itself.
I had a similar issue trying to enable/disable switchery objects after they were created so I set up a global array of switchery objects and added functions to control their state like this:
var switchery_objs = [];
function enableSwitchery(id) {
switchery_objs[id].enable();
}
function disableSwitchery(id) {
switchery_objs[id].disable();
}
function toggleSwitchery(id) {
switchery_objs[id].setPosition(true);
switchery_objs[id].handleOnchange(true);
}
function setSwitchery(id, checked) {
if((checked && !switchery_objs[id].isChecked()) || (!checked && switchery_objs[id].isChecked())) {
switchery_objs[id].setPosition(true);
switchery_objs[id].handleOnchange(true);
}
}
if (window.Switchery && $(".js-switch")[0]) {
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function (html) {
switchery_objs[html.getAttribute('id')] = new Switchery(html, {
color: '#26B99A'
});
});
}
With this, you can just call disableSwitchery("foo1");
to mark it as disabled.