sincos
sincos

Reputation: 137

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.

Upvotes: 3

Views: 3560

Answers (4)

Rams
Rams

Reputation: 41

Just add this single line to switch on the toggle

$('.your_class_name').bootstrapToggle('on');

Upvotes: 2

andrepaulo
andrepaulo

Reputation: 816

change() at the end of your event call, as I did.

$('#switchOutput2_AA').prop('checked', !$('#switchOutput2_AA').prop('checked')).change();

Or to make it easier to undersand

var currentValue = $('#switchOutput2_AA').prop('checked');

$('#switchOutput2_AA').prop('checked', !currentValue).change();

Upvotes: 1

sincos
sincos

Reputation: 137

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');

Upvotes: 2

Lunny
Lunny

Reputation: 852

To toggle on

$('#switchOutput2_AA').removeClass('off')

To toggle off

$('#switchOutput2_AA').addClass('off')

Upvotes: 0

Related Questions