Javascript button toggles only one at a time

I am trying to use buttons to filter a list of items on a page.

While one of the buttons is pressed, all the others will be disabled, and then, if I press another, then only this will be turned on, and the rest will be disabled.

I can’t figure out how to switch it, so if the button is already active, it will turn off all buttons, including itself.

Js fiddle

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]);
});
+4
source share
2 answers
$(".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/

+5
source

Why not just use the default class class for your buttons, such as a filter button, so when you want to disable them, just use:

$(".filter-button").addClass("disabled");

, ,

$(".active").on('click', function(){
    $(".filter-button").addClass("disabled");
    $(".active").removeClass("active");
});

UPDATE: . .

0

Source: https://habr.com/ru/post/1625482/


All Articles