Steps for making a toggle button with Bootstrap

Initially, I developed a web application using HTML, CSS, and JavaScript. Later on, I was requested to recreate it using Bootstrap as well. While I managed to complete the task successfully, I encountered an issue where toggle buttons in the web app reverted back to radio buttons (originally checkboxes).

The code snippet for the buttons is as follows:

<label>
  Notifications
  <span class='toggle'>
    <input type='radio'
      class='notifications'
      name='notifications'
      id='notifications' />
  </span>
</li>
<label>
  Preview
  <span class='toggle'>
    <input type='radio'
      class='preview'
      name='preview'
      id='preview' />
  </span>
</li>

In addition, the HTML page is linked to JavaScript and CSS files:

<script src = 'jqtouch.js'></script>
<script src="jquery.js"></script>
<script src="js/bootstrap.js"></script>
<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/bootstrap-responsive.css" rel="stylesheet">

I am looking for a way to modify the code in order to restore the toggle button functionality. Any suggestions would be appreciated.

Answer №1

Initial answer from 2013

A top-notch (unofficial) Bootstrap Switch can be found here.

https://i.sstatic.net/9QTta.png

<input type="checkbox" name="my-checkbox" checked>
$("[name='my-checkbox']").bootstrapSwitch();

This switch allows the use of radio types or checkboxes as toggles. A type attribute has been included in Version 1.8.

You can access the source code on Github here.

Note from 2018

I do not advise utilizing these outdated switch buttons now, as they have consistently had issues with usability, as multiple individuals have observed here.

Instead, consider exploring modern Switches like this one from the React Component framework (although not directly tied to Bootstrap, it can still be integrated into a Bootstrap grid and UI).

Alternative implementations are available for Angular, View, or jQuery.

https://i.sstatic.net/4E0Uu.png

import '../assets/index.less'
import React from 'react'
import ReactDOM from 'react-dom'
import Switch from 'rc-switch'

class Switcher extends React.Component {
  state = {
    disabled: false,
  }

  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    })
  }

  render() {
    return (
      <div style={{ margin: 20 }}>
        <Switch
          disabled={this.state.disabled}
          checkedChildren={'开'}
          unCheckedChildren={'关'}
        />
        </div>
      </div>
    )
  }
}

ReactDOM.render(<Switcher />, document.getElementById('__react-content'))

Native Bootstrap Switches

For information on the native Bootstrap switches, refer to ohkts11's response below.

Answer №2

In the event that you are open to modifying your HTML, you have the option to utilize the data-toggle attribute with <button> elements. Take a look at the Single toggle section within the button examples:

<button type="button" class="btn btn-primary" data-toggle="button">
    Single toggle
</button>

Answer №3

Bootstrap 3 provides functionality to create toggle buttons using either checkboxes or radio buttons: https://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (preset selection)
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="checkbox"> Option 3
  </label>
</div>

Radio buttons

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="radio" name="options" id="option1" checked> Option 1 (preselected)
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option2"> Option 2
  </label>
  <label class="btn btn-primary">
    <input type="radio" name="options" id="option3"> Option 3
  </label>
</div>

To enable these features, make sure to initialize the .btn classes using Bootstrap's JavaScript:

$('.btn').button();

Answer №4

I have been experimenting with manually activating the 'active' class using JavaScript. While not as robust as a complete library, it seems sufficient for simple cases:

var button = $('#myToggleButton');
button.on('click', function () {
  $(this).toggleClass('active');
});

Upon closer examination, the 'active' class is utilized by Bootstrap when the button is pressed, rather than before or after (our scenario), so there should be no conflict in reusing the same class.

Feel free to test this example and let me know if it encounters any issues: http://jsbin.com/oYoSALI/1/edit?html,js,output

Answer №5

If you aim to maintain a compact code base and only require the toggle button for a specific section of your application, it may be beneficial to manage your JavaScript code (using frameworks like AngularJS, vanilla JavaScript, jQuery) on your own while utilizing simple CSS.

For creating a quality toggle button, check out this generator:

Answer №6

A helpful resource for Bootstrap Toggle Button can be found here. See a code snippet example and jsfiddle link below.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <input id="toggle-trigger" type="checkbox" checked data-toggle="toggle">
    <button class="btn btn-success" onclick="toggleOn()">On by API</button>
    <button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
    <button class="btn btn-primary" onclick="getValue()">Get Value</button>
    <script>
      //If you want to change it dynamically
      function toggleOn() {
        $('#toggle-trigger').bootstrapToggle('on')
      }
      function toggleOff() {
        $('#toggle-trigger').bootstrapToggle('off')  
      }
      //if you want get value
      function getValue()
      {
       var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
       console.log(value);
      }
    </script>
Several examples are provided above. Visit the Js Fiddle here and find the source code on GitHub here.

Update 2020 For Bootstrap 4

In 2020, I suggest using bootstrap4-toggle.


<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2e5e415e5e4b5c00445d6e1f001f18001e">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

<link href="https://cdn.jsdelivr.net/gh/gitbrent/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="60020f0f141314120110544d140f07070c0520534e564e51">[email protected]</a>/css/bootstrap4-toggle.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/gh/gitbrent/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ceaca1a1babdbabcafbefae3baa1a9a9a2ab8efde0f8e0ff">[email protected]</a>/js/bootstrap4-toggle.min.js"></script>

<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle" data-onstyle="success">
<button class="btn btn-success" onclick="toggleOn()">On by API</button>
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>
<button class="btn btn-primary" onclick="getValue()">Get Value</button>

<script>
  //If you want to change it dynamically
  function toggleOn() {
    $('#toggle-trigger').bootstrapToggle('on')
  }
  function toggleOff() {
    $('#toggle-trigger').bootstrapToggle('off')  
  }
  //if you want get value
  function getValue()
  {
   var value=$('#toggle-trigger').bootstrapToggle().prop('checked');
   console.log(value);
  }
</script>

Answer №7

If you're looking to add a toggle switch to your website, consider using the CSS Toggle Switch library. All you need to do is include the CSS file and write the JavaScript code on your own: Check out this page for more information

Answer №8

Discover a sleek solution with the Material Design Switch compatible with Bootstrap 3.3.0

Explore this innovative switch design here

Answer №10

If you're on the hunt for a sleek switch or toggle button, look no further. I took Rick's advice and crafted a straightforward Angular directive for it called angular-switch. Not only does this directive offer a Windows-inspired design, but it also boasts a significantly smaller download size (2kb versus 23kb minified css+js) when compared to angular-bootstrap-switch and bootstrap-switch mentioned earlier.

To implement it, start by including the necessary js and css files:

<script src="./bower_components/angular-switch/dist/switch.js"></script>
<link rel="stylesheet" href="./bower_components/angular-switch/dist/switch.css"></link>

Next, activate it in your Angular app:

angular.module('yourModule', ['csComp'
    // other dependencies
]);

You can now utilize it by doing the following:

<switch state="vm.isSelected" 
    textlabel="Switch" 
    changed="vm.changed()"
    isdisabled="{{isDisabled}}">
</switch>

https://i.sstatic.net/ZHIFd.png

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Any recent guide on how to use the flexbox module?

As the Flexible Box Layout module spec continues to evolve, some browsers have implemented multiple versions with varying syntaxes. Despite efforts to find current tutorials, many sources warn of outdated information. In light of potential future changes, ...

A beginner's guide to using Asp.net, jQuery, and JSON: An easy

Currently, I am in the process of learning how to execute a basic server call using Javascript/jQuery. Despite my efforts to find a straightforward tutorial, I have not been successful. The main objective is to transmit a message containing two parameters ...

What steps should I follow to create a Lunr search functionality for Markdown MD files?

Currently, I am in search of a suitable lunr search implementation for my MD (Markdown) documents spread throughout my React/NextJS website. Our website contains a plethora of Markdown docs within both blog and regular "docs" sections, necessitating a robu ...

Redirecting in Next.js without the use of a React component on the page

I need to redirect a page using HTTP programmatically only. The following code achieves this: export const getServerSideProps: GetServerSideProps = async (context) => { return { redirect: { destination: '/', permanent: false, ...

Updates to Firebase data do not automatically reflect in Google Charts

I've successfully connected my Firebase to Google Charts, however I am facing an issue in displaying a 'no data' message when there is no data available. Currently, I have set a Firebase data value of 'NA' for a single user, which ...

Leveraging TypeScript to Access Parameters in React Router

Currently, I am delving into the realm of TypeScript usage in my React projects and I have encountered a stumbling block when it comes to implementing React Router's useParams() feature. My import statement looks like this: import { useParams } from ...

Set up a jQuery datatable using JSON data and dynamically created columns

Is there a way to set up a column in a datatable based on the value of another column? This is my current code: customerDataTable = $('#datatable_tabletools').dataTable({ "bDeferRender": true, "aaData" : customerData, ...

I am encountering an issue with identifying a directory in Node.js

This is my HTML code <div id="done_work_1" class="logo-slide-track"> </div> <script>$.ajax({ url: "/static/home/done/", success: function (data) { $(data).find("a").attr("href&q ...

The credentials in AWS S3Client are failing to load correctly

I encountered an issue with the S3 Client from aws sdk v3: When using the S3Client as outlined in the documentation and providing credentials via environment variables, I received an error message stating The AWS Access Key Id you provided does not exist ...

How can we target every nth child element universally?

I am working with an HTML structure that has a specific layout, and I need to target all odd <span> elements globally without considering their parent elements. Is there a way to style 1, 3, 5, 7, 9 in red color? I attempted to use :nth-child(odd) b ...

Limiting page entry with passport.js and express middleware

My server is set up to authenticate user login. I have successfully redirected users to the success page after authentication (and back to the login page if it fails). However, I am facing an issue with using my own express middleware to restrict access fo ...

Issue with Bing Maps Infobox mouseout event: Problem arises when attempting to change the htmlContent asynchronously

Can anyone provide assistance? I am currently utilizing the latest Bing Maps version (v8), and I have encountered an issue. When creating a custom Infobox and populating its contents using an async request such as setTimeout/ajax, the mouseout event is tr ...

What could be the reason for angularjs not functioning as expected?

After attempting to create a basic JavaScript unit test using angular.js, I encountered failure without understanding the reason behind it. test.html <html> <head> <script src="angular-1.2.21/angular-scenario.js" ng-autotest></ ...

Confirm the validity of a data point within the JSON data package

When we send a request using the HTTP GET method, the API responds with the data. I need to ensure that the values of a specific input key match exactly what was specified in the GET URL. The URL that was used for the request: https://dummy.dns.com/Wells ...

Issue with v-model not connecting to app.js in Laravel and Vue.js framework

Snippet from app.js const app = new Vue({ el: '#app', router, data:{ banana:'' } }); Code found in master.blade.php <div class="wrapper" id="app"> <router-view></router-view> //using Vue ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

What is the best way to retrieve the date and time using the Open Weather API for a specific city

Currently, I am in the process of developing a weather application using React and integrating the Open Weather API. Additionally, I have incorporated an external library for weather icons. The functionality allows users to input a city name and receive t ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

Tips for uploading images in Next.js using Firebase

While following a tutorial on Next.js, I encountered an issue with the outdated version of Firebase being used. Despite trying different solutions from the documentation and various sources, I am still facing an error message while attempting to upload ima ...

What is the most effective approach for annotating TypeScript abstract classes that are dynamically loaded?

I am in the process of developing a library that allows for the integration of external implementations, and I am exploring the optimal approach to defining types for these implementations. Illustration abstract class Creature { public abstract makeN ...