Bootstrap putting checkbox in a dropdown
Here's what we'll build:
HTML
Essentially, we'll look to combine two different sets of Bootstrap controls & styles: Dropdowns & Checkboxes. Inside of each li
, we'll use a label
instead of an a
element, so that we can wrap the checkbox in a label and make the entire row clickable.
<ul class="dropdown-menu checkbox-menu allow-focus">
<li >
<label>
<input type="checkbox"> Cheese
</label>
</li>
</ul>
CSS
We can steal some of the styles normally applied to .dropdown-menu li a
, input and apply them to our label option instead. We'll make the label occupy the full width of the container and fix some label / checkbox alignment issues. Additionally, we'll add styles for .active
and :hover
.
.checkbox-menu li label {
display: block;
padding: 3px 10px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333;
white-space: nowrap;
margin:0;
transition: background-color .4s ease;
}
.checkbox-menu li input {
margin: 0px 5px;
top: 2px;
position: relative;
}
.checkbox-menu li.active label {
background-color: #cbcbff;
font-weight:bold;
}
.checkbox-menu li label:hover,
.checkbox-menu li label:focus {
background-color: #f5f5f5;
}
.checkbox-menu li.active label:hover,
.checkbox-menu li.active label:focus {
background-color: #b8b8ff;
}
JavaScript
Some other housekeeping, we'll manually keep an .active
class flag on each list item to correspond to whether or not the item is checked so we can style it appropriately.
$(".checkbox-menu").on("change", "input[type='checkbox']", function() {
$(this).closest("li").toggleClass("active", this.checked);
});
We'll also want to allow multiple selections by allowing the menu to stay open on internal click events by stopping the event from bubbling up
$(document).on('click', '.allow-focus', function (e) {
e.stopPropagation();
});
Demo in Stack Snippets
$(".checkbox-menu").on("change", "input[type='checkbox']", function() { $(this).closest("li").toggleClass("active", this.checked);});
$(document).on('click', '.allow-focus', function (e) { e.stopPropagation();});
body { padding: 15px;}
.checkbox-menu li label { display: block; padding: 3px 10px; clear: both; font-weight: normal; line-height: 1.42857143; color: #333; white-space: nowrap; margin:0; transition: background-color .4s ease;}.checkbox-menu li input { margin: 0px 5px; top: 2px; position: relative;}
.checkbox-menu li.active label { background-color: #cbcbff; font-weight:bold;}
.checkbox-menu li label:hover,.checkbox-menu li label:focus { background-color: #f5f5f5;}
.checkbox-menu li.active label:hover,.checkbox-menu li.active label:focus { background-color: #b8b8ff;}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" rel="stylesheet"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.js"></script>
<div class="dropdown"> <button class="btn btn-default dropdown-toggle" type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true"> <i class="glyphicon glyphicon-cog"></i> <span class="caret"></span> </button> <ul class="dropdown-menu checkbox-menu allow-focus" aria-labelledby="dropdownMenu1"> <li > <label> <input type="checkbox"> Cheese </label> </li> <li > <label> <input type="checkbox"> Pepperoni </label> </li> <li > <label> <input type="checkbox"> Peppers </label> </li> </ul></div>
Bootstrap dropdown checkbox select
Not the most elegant solution - you will probably want to refine this somewhat, but this might get you started:
$(document).ready(function() {
$("ul.dropdown-menu input[type=checkbox]").each(function() {
$(this).change(function() {
var line = "";
$("ul.dropdown-menu input[type=checkbox]").each(function() {
if($(this).is(":checked")) {
line += $("+ span", this).text() + ";";
}
});
$("input.form-control").val(line);
});
});
});
How can I show the selected items in the label of a Bootstrap dropdown?
You can actually do it very easily in the code you have already - you just need to check the number of selected options before you set the label:
- This line will get the number of selected checkboxes:
numSelected = $(this).parent(".dropdown-menu").find('.cb-element:checked').length;
- Now all you need to do is check if it is
> 1
, and set the button to:
selText = numSelected + " selected";
That's it! (Don't forget that you also need to check if the current checkbox was deselected - you're not currently doing that).
Show "All selected" label:
If you want to get fancy, you can also see if all of the checkboxes are selected and display "all selected" instead, or if 1 is selected then show the label of that one.
totalNumOptions = $(".dropdown-menu .cb-element").length;
$(".dropdown-menu a").change(function() {
// get selected options
selected = $(this).parent(".dropdown-menu").find('.cb-element:checked');
if (selected.length == totalNumOptions || $("input#checkall:checked").length == 1)
// ALL options are selected, of "All checked" is checked
selText = "All selected";
else if (selected.length == 1)
// show text of the SELECTED option (NOTE: not clicked option!)
selText = $(selected[0]).parent().text();
else
// show number of selected options
selText = selected.length + " selected";
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText);
});
Working Example:
// Get the total number of options so we can see if all are checked
// do this outside of handler so we only do it once
var totalNumOptions = $(".dropdown-menu .cb-element").length;
$(".dropdown-menu a").change(function() {
// get number of selected options
selected = $(this).parent(".dropdown-menu").find('.cb-element:checked');
if (selected.length == totalNumOptions ||
$(this).find("input#checkall:checked").length == 1)
// ALL options are selected
selText = "All selected";
else if (selected.length == 1)
//only 1 selected so show the selected option
selText = $(selected[0]).parent().text();
else
// show number of selected options
selText = selected.length + " selected";
$(this).parents('.btn-group').find('.dropdown-toggle').html(selText);
});
// checbox
$('#checkall').change(function() {
$('.cb-element').prop('checked', this.checked);
});
$('.cb-element').change(function() {
if ($('.cb-element:checked').length == $('.cb-element').length) {
$('#checkall').prop('checked', true);
} else {
$('#checkall').prop('checked', false);
}
});
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<div class="btn-group ">
<button class="btn btn-secondary dropdown-toggle text-center" type="button" data-toggle="dropdown">
Dropdown button
</button>
<div class="dropdown-menu">
<a class="dropdown-item"><input type="checkbox" name="all" class="mr-2" id="checkall">Check All</br>
</a>
<a class="dropdown-item"><input type="checkbox" class="cb-element mr-2"> Checkbox 1</a>
<a class="dropdown-item"><input type="checkbox" class="cb-element mr-2"> Checkbox 2</a>
<a class="dropdown-item"><input type="checkbox" class="cb-element mr-2"> Checkbox 3</a>
</div>
</div>
how reset all checkbox in bootstrap dropdown
You can do it like this:
$("#dropdownMenuButton").click(function() {
$('.dropdown-menu.show input[type="checkbox"]').prop('checked', false);
});
This will clear all the checkbox once you click on the dropdown.
Demo
$('input[type="checkbox"]').prop('checked', false);
$("#dropdownMenuButton").click(function() {
$('.dropdown-menu.show input[type="checkbox"]').prop('checked', false);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Dropdown button
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item"><input type="checkbox">Action</a>
<a class="dropdown-item"><input type="checkbox">Another action</a>
<a class="dropdown-item"><input type="checkbox">Something else here</a>
</div>
</div>
Get id of checked checkbox in Bootstrap dropdown inside UL, LI, and Label, then set others based on it being checked or not
As far as I understand your code should be something like this:
$(document).ready(function() {
const $checkboxMenu = $(".checkbox-menu");
/* might have to do this inside the event listener depending on
*how many .checkbox-menu you have, this will work for the purpose of this demo.
*/
const $otherCheckboxes = $checkboxMenu.find(':checkbox').not('#allbox');
$checkboxMenu.on("change", ":checkbox", function() {
$(this).closest("li").toggleClass("active", this.checked);
if (this.id === 'allbox') {
$otherCheckboxes
.prop('checked', this.checked)
.prop('disabled', !this.checked);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dropdown">
<button class="btn btn-primary dropdown-toggle" type="button" id="dropdownMenu1" data- toggle="dropdown" aria-haspopup="true" aria-expanded="true">Parameter Selection
<span class="caret"></span>
</button>
<ul class="dropdown-menu checkbox-menu allow-focus" id="boxlist">
<li>
<label><input type="checkbox" name="windbox" id="windbox">Wind</label>
</li>
<li>
<label><input type="checkbox" name="visbox" id="visbox">Visibility</label>
</li>
<li>
<label><input type="checkbox" name="cloudbox" id="cloudbox">Clouds</label>
</li>
<li>
<label><input type="checkbox" name="pwbox" id="pwbox">Present Weather</label>
</li>
<li>
<label><input type="checkbox" name="tempbox" id="tempbox">Air Temperature</label>
</li>
<li>
<label><input type="checkbox" name="dewbox" id="dewbox">Dew Point</label>
</li>
<li>
<label><input type="checkbox" name="altbox" id="altbox">Altimeter</label>
</li>
<li>
<label><input type="checkbox" name="slpbox" id="slpbox">Sea-Level Pressure</label>
</li>
<li>
<label><input type="checkbox" name="precipbox" id="precipbox">Precip</label>
</li>
<li>
<label><input type="checkbox" name="allbox" id="allbox" class="all-box">ALL</label>
</li>
</ul>
</div>
How to avoid dropdown menu hiding while click on checkbox inside the dropdown list items?
Add onClick={(e) => e.stopPropagation()}
in <Form.Check>...</Form.Check>
.e.stopPropagation()
in tag will help this tag prevent onClick event from parent.
Code here: https://codesandbox.io/s/dropdown-with-checkbox-forked-88h9m6?file=/src/App.js
import "./styles.scss";
import "bootstrap/dist/css/bootstrap.min.css";
import { Dropdown, Form } from "react-bootstrap";
export default function App() {
return (
<div className="App">
<Dropdown className="dropdown-groove">
<Dropdown.Toggle variant="outline-secondary " id="dropdown-basic">
Select...
<label className="dropdown-label">Dropdown label</label>
</Dropdown.Toggle>
<Dropdown.Menu>
<Dropdown.Item href="#/action-1">
{" "}
<Form.Check
onClick={(e) => e.stopPropagation()} //<=== Add here
className="checkbox-groove"
inline
label="Unselected"
name="group1"
type="checkbox"
/>{" "}
</Dropdown.Item>
<Dropdown.Item href="#/action-2">List Item 2</Dropdown.Item>
<Dropdown.Item href="#/action-3">List Item 3</Dropdown.Item>
<Dropdown.Item href="#/action-4">List Item 4</Dropdown.Item>
<Dropdown.Item href="#/action-5">List Item 5</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
</div>
);
}
How to get Dropdown Menu with Checkboxes
Can easily get from a google search,
Try this
HTML
<br/>
<div class="container">
<div class="row">
<div class="col-lg-12">
<div class="button-group">
<button type="button" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown"><span class="glyphicon glyphicon-cog"></span> <span class="caret"></span></button>
<ul class="dropdown-menu">
<li><a href="#" class="small" data-value="option1" tabIndex="-1"><input type="checkbox"/> Option 1</a></li>
<li><a href="#" class="small" data-value="option2" tabIndex="-1"><input type="checkbox"/> Option 2</a></li>
<li><a href="#" class="small" data-value="option3" tabIndex="-1"><input type="checkbox"/> Option 3</a></li>
<li><a href="#" class="small" data-value="option4" tabIndex="-1"><input type="checkbox"/> Option 4</a></li>
<li><a href="#" class="small" data-value="option5" tabIndex="-1"><input type="checkbox"/> Option 5</a></li>
<li><a href="#" class="small" data-value="option6" tabIndex="-1"><input type="checkbox"/> Option 6</a></li>
</ul>
</div>
</div>
</div>
</div>
JS
var options = [];
$( '.dropdown-menu a' ).on( 'click', function( event ) {
var $target = $( event.currentTarget ),
val = $target.attr( 'data-value' ),
$inp = $target.find( 'input' ),
idx;
if ( ( idx = options.indexOf( val ) ) > -1 ) {
options.splice( idx, 1 );
setTimeout( function() { $inp.prop( 'checked', false ) }, 0);
} else {
options.push( val );
setTimeout( function() { $inp.prop( 'checked', true ) }, 0);
}
$( event.target ).blur();
console.log( options );
return false;
});
or check this,
Related Topics
Grabbing Style.Display Property via Js Only Works When Set Inline
Animating Max-Height with Pure Js
Semantic-Ui Modal Size Keeps Extending to the Height of a Page
Animation for Newly Rendered Elements, But Not on Page Load
How to Detect State of CSS Transition via Js and Skip It
Attempt to Add a Rule to a CSS Stylesheet Gives "The Operation Is Insecure" in Firefox
Fiill the Space Between Two Text Elements with Dots
Fiill the Space Between Two Text Elements with Dots
Angular - Ngfor* Four Elements on Row
How to Get Jquery or JavaScript to Change CSS Based on the Current Url
Dynamically Modify Webkit Animation with JavaScript
Jquery Click Event Only Working After Moving the Mouse in Chrome
How to Let a Div Stick to Cursor
How to Grab the CSS Truncated Text via Jquery
Onclick JavaScript Function Working Only on Second Click
Jquery Click Event Only Working After Moving the Mouse in Chrome