I have multiple checkboxes on the page that are converted into Switcheries like this:
$(document).ready(function () {
$("input[type=checkbox]").each(function (index, element) {
var init = new Switchery(element, {
size: 'small', color: '#477FC5', secondaryColor: '#CCCCCC'
});
});
});
So I have eventually the markup:
<input type="checkbox" id="checkbox_1" value="baz" data-switchery="true" style="display: none;">
<span class="switchery switchery-small" style="box-shadow: rgb(71, 127, 197) 0px 0px 0px 11px inset;">
<small style="left: 13px; transition: background-color 0.4s, left 0.2s; background-color: rgb(255, 255, 255);"></small>
</span>
<input type="checkbox" id="checkbox_2" value="baz" data-switchery="true" style="display: none;">
<span class="switchery switchery-small" style="box-shadow: rgb(71, 127, 197) 0px 0px 0px 11px inset;">
<small style="left: 13px; transition: background-color 0.4s, left 0.2s; background-color: rgb(255, 255, 255);"></small>
</span>
<input type="checkbox" id="checkbox_3" value="baz" data-switchery="true" style="display: none;">
<span class="switchery switchery-small" style="box-shadow: rgb(71, 127, 197) 0px 0px 0px 11px inset;">
<small style="left: 13px; transition: background-color 0.4s, left 0.2s; background-color: rgb(255, 255, 255);"></small>
</span>
I want to dynamically disable or enable these switcheries after some events. But I cannot correctly select the switchery to disable, because there are multiple switcheries on the page, and the following code does not work for me:
$(".main-checkbox").change(function () {
var id = 3;
var switchery = new Switchery($("#checkbox_" + id));
if ($(this).is(":checked")) {
switchery.disable();
} else {
switchery.enable();
}
});
What can I do to make it work as expected?
When you create a new instance of Switchery you can save it in a map like:
In this way, when you need to use the Switchery for the current element you can get the instance:
The snippet: