sincos sincos - 7 months ago 84
Javascript Question

change toggle dynamically using bootstraptoggle

I'm using this toggle from that plugin http://www.bootstraptoggle.com/

I would like to change the value dynamically with data from database.

Here's my toggle

<input id="switchOutput2_AA" name="switchOutput2_AA" <?php echo ($output2 == 2 ? 'checked' : '')?> type="checkbox" data-toggle="toggle" data-on="<?php echo _("ON") ?>" data-off="<?php echo _("OFF")?>" data-onstyle="success" data-offstyle="danger" value="1">


Here's my jquery code
I've tried this :

$( '#switchOutput2_AA' ).addClass('toggle-on');
$( '#switchOutput2_AA' ).removeClass('toggle-off');


and also tried that :

$( '#switchOutput2_AA').prop('checked', true);


Any idea? Thx.

Answer

I found the answer. We have to change the class on the parent div of the input. This parent is created by the bootstraptoggle plugin, so you don't have it in your code...

My code is

<input id="switchOutput2_AA" name="switchOutput2_AA" checked type="checkbox" data-toggle="toggle" data-on="ON" data-off="OFF" data-onstyle="success" data-offstyle="danger" value="1">    

But, when debugging, what is created by the plugin, it's :

<div class="toggle btn btn-success" data-toggle="toggle" style="width: 65px; height: 34px;">
    <input id="switchOutput2_AA" checked="" type="checkbox" data-toggle="toggle" data-on="ON" data-off="OFF" data-onstyle="success" data-offstyle="danger" value="1">
    <div class="toggle-group">
        <label class="btn btn-success toggle-on">ON</label>
        <label class="btn btn-danger active toggle-off">OFF</label>
        <span class="toggle-handle btn btn-default"></span>
    </div>
 </div>

When we want to switch the toggle ON :

$( '#switchOutput1_AA' ).parent().removeClass('off');
$( '#switchOutput1_AA' ).parent().removeClass('btn-danger');
$( '#switchOutput1_AA').parent().addClass('btn-success');

And to switch to toggle OFF :

$( '#switchOutput1_AA' ).parent().addClass('off');
$( '#switchOutput1_AA' ).parent().removeClass('btn-success');
$( '#switchOutput1_AA' ).parent().addClass('btn-danger');