How to create a toggle button in Bootstrap
Initial answer from 2013
An excellent (unofficial) Bootstrap Switch is available.
<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.
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.
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>
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 .btn
s with Bootstrap's Javascript:
$('.btn').button();