Reputation: 43
I'm trying to use buttons to filter a list of elements in a page.
So far if one of the buttons is clicked all the others will be disabled and then if I click a different one then only that will be enabled and the others will be disabled.
I cannot work out how to toggle it so if the button was already active it would un-disable all buttons including itself.
html:
<div class="calendar-filter">
<a href="#" class="dnco calendar-color-key btn btn-raised"><i class="material-icons"></i>Duty NCO</a>
<a href="#" class="main calendar-color-key btn btn-raised"><i class="material-icons"></i>Main Cadets</a>
<a href="#" class="wmt calendar-color-key btn btn-raised"><i class="material-icons"></i>Wing Marching Team</a>
<a href="#" class="juniors calendar-color-key btn btn-raised"><i class="material-icons"></i>Juniors</a>
<a href="#" class="exercise calendar-color-key btn btn-raised"><i class="material-icons"></i>Exercise</a>
<a href="#" class="other calendar-color-key btn btn-raised"><i class="material-icons"></i>Other</a>
</div>
js:
function filterButtonClick(buttonClass) {
$('.calendar-color-key').each(function() {
$(this).addClass('disabled');
if($(this).hasClass(buttonClass)) {
$(this).removeClass('disabled');
}
});
}
$('.calendar-color-key').on('click', function() {
var filterButtonClasses = this.classList;
filterButtonClick(filterButtonClasses[0]);
});
Upvotes: 4
Views: 3737
Reputation: 9391
$(".calendar-color-key").click(function() { //select by class
var clicked = $(this);
if (clicked.hasClass('toggle')) {
$('.calendar-color-key').removeClass('disabled'); //enable all again
clicked.removeClass('toggle');
} else {
$('.calendar-color-key').removeClass('toggle');
clicked.addClass('toggle');
clicked.removeClass('disabled');
$('.calendar-color-key').not(clicked).addClass('disabled'); //disable everything except clicked element
}
});
https://jsfiddle.net/6kx8ncdb/2/
Upvotes: 5
Reputation: 73
Why not just use a class default class for your buttons like filter-button so when you want to disable them all just use:
$(".filter-button").addClass("disabled");
And use an active class it would be a big help so you can have
$(".active").on('click', function(){
$(".filter-button").addClass("disabled");
$(".active").removeClass("active");
});
UPDATE: don't forget to remove the active class when adding disabled I updated the code.
Upvotes: 0