How do I programatically change a jQuery Switchery checkbox state from checked to unchecked (and vice versa)?
I tried using global_switch_sound.prop('checked', true)
on the checkbox element but it doesn't work.
HTML:
<input id="sound-active-input" type="checkbox" />
JavaScript:
global_switch_sound = new Switchery(document.querySelector('#sound-active-input'));
Try this:
$('.switchery').click();
It should trigger a click and switch. OR this:
$('.switchery').trigger('click');
If anyone is like me and wanted a solution that goes beyond ".click()"ing the DOM. The following function takes the Switchery object and a boolean to indicate whether the switch should be checked or unchecked(true/ false respectively):
function setSwitchery(switchElement, checkedBool) {
if((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
switchElement.setPosition(true);
switchElement.handleOnchange(true);
}
}
Example usage:
var mySwitch = new Switchery($('#mySwitchCheck')[0], {
size:"small",
color: '#0D74E9'
});
//Checks the switch
setSwitchery(mySwitch, true);
//Unchecks the switch
setSwitchery(mySwitch, false);
Hope this helps someone else
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With