ChatGPT解决这个技术问题 Extra ChatGPT

How to create a toggle button in Bootstrap

I originally created a web app in HTML, CSS and JavaScript, then was asked to create it again in Bootstrap too. I've done it all fine, but I had toggle buttons in the web app that have changed back to radio (originally checkbox) buttons instead of the toggle buttons I had originally.

The code for the buttons is:

<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>

and the JavaScript and CSS files that the HTML page is linked to are:

<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">

Is there a way to change the code so I can get the toggle button back?

i appreciate the link, but it doesn't have what I'm looking for. the toggle button i had was he kind you'd see on an iphone, like the 'on'/'off' kind. does that make sense?
ok so it is related to jqtouch.js and not to bootstrap itself i think
ok. it's on github if that's easier, though.
LOL man i see an infinite list of files :) can't you be more specific? :D

s
smonff

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

https://i.stack.imgur.com/9QTta.png

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

It uses radio types or checkboxes as switches. A type attribute has been added since V.1.8.

Source code is available on Github.

Note from 2018

I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.

Please consider having a look at modern Switches like this one from the React Component framework (not Bootstrap related, but can be integrated in Bootstrap grid and UI though).

Other implementations exist for Angular, View or jQuery.

https://i.stack.imgur.com/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

See ohkts11's answer below about the native Bootstrap switches.


I'd avoid those switches: ux.stackexchange.com/questions/1318/…
This site no longer exists
You're right @w3bMak3r, the domain name has been changed. Updated.
It's a nice plugin. easy to use. but problem with safari 5.1.7. When I click once, another are moving. can anybody solve this?
Bootstrap Toggle is another bootstrap-based alternative
S
Sam

If you don't mind changing your HTML, you can use the data-toggle attribute on <button>s. See the Single toggle section of the button examples:

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

Is there a way to have an internal checkbox in a single-toggle just like in the checkbox/radio option?
aria-pressed="true" can be used to check state
S
StriplingWarrior

Bootstrap 3 has options to create toggle buttons based on checkboxes or radio buttons: http://getbootstrap.com/javascript/#buttons

Checkboxes

<div class="btn-group" data-toggle="buttons">
  <label class="btn btn-primary active">
    <input type="checkbox" checked> Option 1 (pre-checked)
  </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>

For these to work you must initialize .btns with Bootstrap's Javascript:

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

Is there a way to have an internal checkbox in a single-toggle just like in the checkbox/radio option?
@Shimmy: If you just put a single checkbox into a button group, you'd get the same behavior. I'm not aware of any less-verbose way to get a checkbox-backed single-toggle.
佚名

I've been trying to activate 'active' class manually with javascript. It's not as usable as a complete library, but for easy cases seems to be enough:

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

If you think carefully, 'active' class is used by bootstrap when the button is being pressed, not before or after that (our case), so there's no conflict in reuse the same class.

Try this example and tell me if it fails: http://jsbin.com/oYoSALI/1/edit?html,js,output


I think the user did not ask about it, but your response just answered my question!
I think it would have been the user's next question anyway.
R
Rick

If you want to keep a small code base, and you are only going to be needing the toggle button for a small part of the application. I would suggest instead maintain you're javascript code your self (angularjs, javascript, jquery) and just use plain CSS.

Good toggle button generator: https://proto.io/freebies/onoff/


M
Muhammet Can TONBUL

Here this very usefull For Bootstrap Toggle Button . Example in code snippet!! and jsfiddle below.

I showed you a few examples above. I hope it helps. Js Fiddle is here Source code is avaible on GitHub.

Update 2020 For Bootstrap 4

I recommended bootstrap4-toggle in 2020.


Short, and to the Point, quick and easy solution, you made my day!
O
OMA

You can use the CSS Toggle Switch library. Just include the CSS and program the JS yourself: http://ghinda.net/css-toggle-switch/bootstrap.html


While this may answer the question, it is better to provide the actual information here and not just a link. Link-only answers are not considered good answers and will probably be deleted.
But this is not a link to an explanation. It's a link to an actual library, which I'm mentioning the name of in my answer. Do you really want me to post the whole library source code here? My answer would only be wrong if I just said "use this library: [link]" without mentioning the name of the library, but since I'm mentioning the name, I think the answer is appropriate since if the link goes bad, he/she can try to download the library from somewhere else, since the name is known.
You don't have to post the entire library's source code, but at the very least you need to offer some insight into how to use it. "Just include the CSS and program the JS yourself" isn't much to go on and isn't likely to help OP or other users.
Well, it's really that easy to use! Just include one of the CSS code samples and then program the JS with whatever you want to do. I can't comment on the actual JS programming, since the original poster didn't ask for an specific action to be performed when using the toggle button, so what else can I say about it? Also, why is the accepted answer considered OK? It's also a "link-only" answer! (it just says "Not sure if it helps, but an excellent (unofficial) Bootstrap Switch is available. It uses radio types though"). Why is that answer OK? You didn't comment about its link-only nature there.
I
Ivan Rodriguez

You can use the Material Design Switch for Bootstrap 3.3.0

http://bootsnipp.com/snippets/featured/material-design-switch


o
ohkts11

Bootstrap 4 solution

bootstrap 4 ships built-in toggle. Here is the documentation. https://getbootstrap.com/docs/4.3/components/forms/#switches

https://i.stack.imgur.com/ynRNC.png


looks like Bootstrap 4.3 and up only
T
T J

In case someone is still looking for a nice switch/toggle button, I followed Rick's suggestion and created a simple angular directive around it, angular-switch. Besides preferring a Windows styled switch, the total download is also much smaller (2kb vs 23kb minified css+js) compared to angular-bootstrap-switch and bootstrap-switch mentioned above together.

You would use it as follows. First include the required js and css file:

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

And enable it in your angular app:

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

Now you are ready to use it as follows:

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

https://i.stack.imgur.com/ZHIFd.png