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?

推荐答案

Initial answer from 2013

An excellent (unofficial) Bootstrap Switch is available.

Classic 2013 Switch

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

源代码是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).

Angular、View或jQuery还有其他实现.

Modern 2018 Switch

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

关于native Bootstrap switches,请参见下面的ohkts11's answer.

Jquery相关问答推荐

逐个交换图像

使用 Ajax 列出数据(仅显示最后的数据)

更改后如何使用 jQuery Select CSS 类

如何使 Bootstrap 轮播滑块使用移动左/右滑动

如何使 jQuery.ready 中定义的函数在全局可用?

为什么要两次声明 jQuery?

动态设置 iframe src

moment.js isValid 函数无法正常工作

如何使用 jQuery Select sibling 元素?

iframe 仅显示页面的特定部分

用jquery替换锚文本

使用 jquery 通过文本设置下拉值

测试两个元素是否相同

CORS POST 请求可以使用纯 JavaScript,但为什么不使用 jQuery?

订单对象是否由指定的 jQuery Select 器返回?

如何在 TypeScript 中获得 jQuery 自动完成功能?

将多个 JavaScript 文件合并为一个 JS 文件

在jQuery中获取列表元素内容的数组

将十六进制转换为 RGBA

fancybox2 / fancybox 导致页面跳转到顶部