Create Inline Checkbox & Radio Buttons In Bootstrap - TWS Toggle Buttons

Create Inline Checkbox & Radio Buttons In Bootstrap - TWS Toggle Buttons
File Size: 11.9 KB
Views Total:
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A small jQuery plugin for Bootstrap 3/4 that transforms the normal checkbox and radio inputs into user-friendly toggle buttons using Bootstrap's Button Group component.

How to use it:

1. Include the Bootstrap's stylesheet in the header section of the webpage.

<link rel="stylesheet" href="/path/to/bootstrap.min.css">

2. Include jQuery library and the jQuery TWS Toggle Buttons plugin at the bottom of the webpage.

<script src="//code.jquery.com/jquery.min.js"></script>
<script src="jquery.twbs-toggle-buttons.min.js"></script>

3. Insert your checboxes and radio buttons into Bootstrap Button Group elements as follows:

<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn active" role="button">
    <input type="radio" name="options" value="1" required="required">YES
  </label>
  <label class="btn" role="button">
    <input type="radio" name="options" value="0">NO
  </label>
</div>

<div class="btn-group btn-group-toggle" data-toggle="buttons">
  <label class="btn active" role="button">
    <input type="checkbox" name="options[]" value="1">Option 1
  </label>
  <label class="btn active" role="button">
    <input type="checkbox" name="options[]" value="2">Option 2
  </label>
  <label class="btn" role="button">
    <input type="checkbox" name="options[]" value="3">Option 3
  </label>
</div>

4. Call the function and the plugin will do the rest.

$(".btn-group-toggle").twbsToggleButtons();

5. Config the toggle buttons using the following HTML data attributes:

  • data-twbs-toggle-buttons-class-active: CSS class when the toggle button is active.
  • data-twbs-toggle-buttons-class-inactive: CSS class when the toggle button is inactive.

6. Customize the active/inactive classes.

$(".btn-group-toggle").twbsToggleButtons({
  classActive: "btn-success",
  classInactive: "btn-secondary"
});

7. Overide the default selector.

$(".btn-group-toggle").twbsToggleButtons({
  twbsBtnSelector: "[role='button']"
});

8. Trigger a function after the state is changed.

$(".btn-group-toggle").on("twbsToggleButtons:activate", function (e){
  console.log(e);
});

Changelog:

2019-07-29

  • Workaround for checkbox buttons when using latest bootstrap (not alpha): Remove attribute "aria-pressed" and class active manually to deactivate a checkbox button.
  • FixedWorkaround for radio and checkbox buttons when using latest bootstrap (not alpha): Add attribute "aria-pressed" and class active manually to activate a radio and checkbox button.

This awesome jQuery plugin is developed by prokki. For more Advanced Usages, please check the demo page or visit the official website.