I have a Bootstrap dropdown that has checkboxes in the options. When I select one checkbox, the checkbox text is showing in dropdown button.
The problem is that it is not working the way I want when multiple checkboxes are selected. When I select two checkboxes, the text of the last clicked checkbox is showing. This should not be there, instead of the checkbox text I want it to show "Selected 2 items" in dropdown button.
How can I solve this problem?
$(".dropdown-menu a").click(function() {
var selText = $(this).text();
$(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>