Search code examples
jquery-uitoggleswitch

jquery toggle switch programmatcally on off


Hi Im using jquery ui toggleswitch toggleswitch.js I can get on off value but

how can i set on /off value programmatically in javascript or jquery

i'm using this code on change but i want to set it on document ready

  $('.toggleEmailStatus').toggleSwitch().change(function (ev) {
        alert(ev);
        try {

            console.log("value= " + $(this).val());

        } catch (e) {
            alert(e);
        }     
 });

Solution

  • You can programmatically turn it on or off by triggering a click on the respective checkbox:

    jQuery(document).ready(function($) {
      $('.toggleswitch').toggleSwitch();
      $("#opt2").trigger("click"); // turn it on
    });
    <link href="https://raw.githack.com/jamiebicknell/Toggle-Switch/master/toggleswitch.css" rel="stylesheet" />
    <script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js'></script>
    <script type='text/javascript' src='https://raw.githack.com/jamiebicknell/Toggle-Switch/master/jquery.toggleswitch.js'></script>
    <label for='opt1'>Option 1</label>
    <input type='checkbox' name='opt1' id='opt1' value='1' class='toggleswitch' checked='checked' />
    
    <!-- Switch is OFF -->
    <label for='opt2'>Option 2 (off by default)</label>
    <input type='checkbox' name='opt2' id='opt2' value='1' class='toggleswitch' />