Search code examples
jquerytwitter-bootstrapbootstrap-switch

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


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

Solution

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