Reputation: 27
I have the following code: jQuery + Bootstrap
https://jsfiddle.net/a27rffb2/4/
jQuery Element:
$(document).ready(function() {
$('input:checkbox').change(function() {
if ($("#toggle1").is(":checked")) {
$("#collapseOneC1").collapse('show');
$("#collapseTwoC1").collapse('show');
$("#collapseThreeC1").collapse('show');
} else {
$("#collapseOneC1").collapse('hide');
$("#collapseTwoC1").collapse('hide');
$("#collapseThreeC1").collapse('hide');
}
});
//Toggle on Element Collapse
$("#collapseOneC1, #collapseTwoC1, #collapseThreeC1").on('shown.bs.collapse', function() {
$('#toggle1').prop("checked", true);
});
$("#collapseOneC1, #collapseTwoC1, #collapseThreeC1").on('hidden.bs.collapse', function() {
$('#toggle1').prop("checked", false);
});
});
Problem Statement: The toggle switch should be checked only if all option panels are shown (When you click on option panel to open individually). How can this be achieved by editing the above code?
Thanks for reviewing!!
Upvotes: 0
Views: 73
Reputation: 101
Please check the updated code: https://jsfiddle.net/KlaussU/a27rffb2/6/
if(areAllOptionsExpanded()) {
$('#toggle1').prop("checked", true);
}
function areAllOptionsExpanded() {
return $(".card-header.collapsed").length == 0;
}
I think this is a better solution since you will not have to manually add $('#collapseOneCX').hasClass('show') for every option you might want to add in the future (or remove). Even if you think you will not need to do that you can still not be 100% sure so it's better to write a more general solution that would not require you to do any changes in the future.
Upvotes: 1
Reputation: 9738
You need to add a condition to check if all options are shown, which means you need to check if they all have the class .show using JQuery function .hasClass()
if ($('#collapseOneC1').hasClass('show') && $('#collapseTwoC1').hasClass('show') && $('#collapseThreeC1').hasClass('show')) {
$('#toggle1').prop("checked", true);
}
Upvotes: 1