const containerSelector = '.choose-buttons';
const buttonSelector = '.btn';
const activeClass = 'active';
const maxActive = 3;
$(containerSelector).on('click', buttonSelector, function(e) {
const numActive = $(`${buttonSelector}.${activeClass}`, e.delegateTarget).length;
const $this = $(this);
if (numActive < maxActive || $this.hasClass(activeClass)) {
$this.toggleClass(activeClass);
}
});
// или
document.querySelectorAll(containerSelector).forEach(n => {
n.addEventListener('click', onClick);
});
function onClick(e) {
const button = e.target.closest(buttonSelector);
if (button) {
const active = [...this.querySelectorAll(`${buttonSelector}.${activeClass}`)];
if (active.length < maxActive || active.includes(button)) {
button.classList.toggle(activeClass);
}
}
}