Bootstrap Switch - How can i change a div`s style depending on the toggle`s state?

2.3k views Asked by At

I`m fairly new to jQuery and I ran into a problem with Bootstrap Switch.

here is my fiddle: http://jsfiddle.net/egqjvz7b/3/

I have two divs with the same class but different ids. Both of the divs have toggle switches under them. What I want to do is when I switch the first toggle the first div class changes from 'box' to 'selectedbox' then if I switch over to the second toggle the first div goes back to the original class and the second div changes to 'selectedbox'.

Between 'box' and 'selectedbox' only the box-shadow is different so i`m also happy to change just that.

Hope I was clear and somebody could help. Cheers!

html

<body>

<div class="box" id="option1">
<p>Option 1</p>
</div>

<input type="radio" name="exampleToggle" id="toggleOption1" data-on-text="Selected" data-off-text="Select" data-on-color="success" data-off-color="primary" data-inverse="true">

<div class="box" id="option2">
<p>Option 2</p>
</div>

<input type="radio" name="exampleToggle" id="toggleOption2" data-on-text="Selected" data-off-text="Select" data-on-color="success" data-off-color="primary" data-inverse="true">

</body>

css

body{
margin: 30px;
}

.box{
background: rgba(255, 255, 255, 0.6);
border-radius: 5px;
border-top: solid 3px #18bc9c;
box-shadow: 0px 2px 5px #2c3e50;
padding:20px;
height:100px;
width:100px;
margin: 30px 0;
}

.selectedbox{
background: rgba(255, 255, 255, 0.6);
border-radius: 5px;
border-top: solid 3px #18bc9c;
box-shadow: 0px 0px 20px #18bc9c;
padding:20px;
height:100px;
width:100px;
margin: 30px 0;
}

js

$("[name='exampleToggle']").bootstrapSwitch();
3

There are 3 answers

1
Leo Silence On BEST ANSWER

this is a simple DEMO you can try.

add data-id to radio buttons like:

<input type="radio" name="exampleToggle" id="toggleOption1"  data-id="#option1"...../>
<input type="radio" name="exampleToggle" id="toggleOption2"  data-id="#option2"...../>

and

$("[name='exampleToggle']").bootstrapSwitch({
    onSwitchChange: function(event, state){
        var id = $(this).data('id');
       $(id + ', .selectedbox').toggleClass('box selectedbox');

    }
});
1
R.A. Lucas On

The jQuery toggleClass or the addClass and removeClass methods should work. And it looks like there's an onSwitchChange method from bootstrap-switch that should give you the event trigger, so something like this:

$("#toggleOption1").onSwitchChange(function(evt, state) {
   $('#option1").toggleClass('selectedBox');
});

And similar for the other option. Hope this helps.

1
Matt Shade On
$("[name='exampleToggle']").on('switchChange.bootstrapSwitch',     function(event, state) {    
    $(this).parent().parent().prev('.box').toggleClass("boxSelected");    
});

bootstrap wraps the switch a few times so you need to traverse up. If the markup is going to stay the same you could do it this way.