Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing a Switchery checkbox state from code

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'));
like image 530
Idan Shechter Avatar asked Feb 21 '14 10:02

Idan Shechter


2 Answers

Try this:

$('.switchery').click();

It should trigger a click and switch. OR this:

$('.switchery').trigger('click');
like image 135
Rickert Avatar answered Oct 22 '22 00:10

Rickert


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

like image 32
Tom G Avatar answered Oct 22 '22 00:10

Tom G