Open In App

How to add bootstrap toggle-switch using JavaScript ?

Bootstrap toggle-switch is a simple component used for activating one of the two given options. Commonly used as an on/off button.

The CSS framework is a library that allows for easier, more standards-compliant web design using the Cascading Style Sheets language. Bootstrap 4 is one such widely used CSS framework used by web developers for building user-friendly interactive web applications. Bootstrap along with JavaScript helps develop a responsive user interface. 



Approach:

The code snippet below demonstrates a toggle switch using JavaScript.



Example:
 




<!DOCTYPE html>
<html>
  
<head>
  
    <link rel="stylesheet" href=
        integrity=
"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" 
        crossorigin="anonymous">
  
    <script src=
    </script>
  
    <script src=
    </script>
  
    <link href=
         rel="stylesheet"/>
</head>
  
<body>
    <div class="container mt-5">
  
        <!--Initialize toggles with id toggle-one
            with JavaScript.-->
        <input type="checkbox" id="toggle-one">
  
        <script>
            $(function() {
                $('#toggle-one').bootstrapToggle({
                    on: 'Enabled',
                    off: 'Disabled'
                });
            })
        </script>
    </div>
</body>
  
</html>

Output:

Alternate approach:

Example:




<!DOCTYPE html>
<html>
  
<head>
  
    <link rel="stylesheet" href=
        integrity=
"sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" 
        crossorigin="anonymous">
  
    <script src=
    </script>
      
    <script src=
    </script>
  
    <link href=
        rel="stylesheet"/>
</head>
  
<body>
    <div class="container mt-5">
        <input id="toggle-trigger" type="checkbox" 
            data-toggle="toggle">
  
        <button class="btn btn-success" onclick="toggleOn()">
            On Button
        </button>
  
        <button class="btn btn-danger" onclick="toggleOff()">
            Off Button
        </button>
  
    </div>
    <script>
        function toggleOn() {
            $('#toggle-trigger').bootstrapToggle('on')
        }
        function toggleOff() {
            $('#toggle-trigger').bootstrapToggle('off')  
        }
    </script>
</body>
  
</html>

Output:


Article Tags :