Liam
Liam

Reputation: 281

How to use Bootstrap Toggle to toggle another Bootstrap Toggle

I'm having an issue with bootstrap's toggle functionality.

The idea is to have a checkbox (bootstrap toggle) toggle a second checkbox (bootstrap toggle) on or off. Sadly, it has not been working on the webpage. I've noticed that by removing "data-toggle='toggle'" the function works, but even an alert to the onclick() event isn't responding.

function toggleOnByInput() {
    $('#toggle-trigger').prop('checked', true).change()
 }
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>
<script src="jquery-3.2.1.min.js"></script>
<input 
        type="checkbox" 
        id="week" 
        name="week" 
        data-toggle="toggle"                 
        data-onstyle="success" 
        data-offstyle="warning" 
        data-size="small"
        data-on="Yes" 
        data-off="No"
        onclick="toggleOnByInput()">

<input id="toggle-trigger" type="checkbox" data-toggle="toggle">

Upvotes: 3

Views: 1550

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

1.jQuery library need to added first before any other js library.

2.Check that jQuery library file path is correct.Otherwise file will not included and your code will not work.

3.Since you are using bootstrap toogle so onclick will not work. You have to use below code:-

$('body').on('click','.toggle-group:first',function(){
    $('.toggle-group:last').click();
});

I did these changes and code started working fine:-

$('body').on('click','.toggle-group:first',function(){
  $('.toggle-group:last').click();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
<link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet"/>

<input 
        type="checkbox" 
        id="week" 
        name="week" 
        data-toggle="toggle"                 
        data-onstyle="success" 
        data-offstyle="warning" 
        data-size="small"
        data-on="Yes" 
        data-off="No">

<input id="toggle-trigger" type="checkbox" data-toggle="toggle">

Upvotes: 2

Related Questions