0

Добрый день есть такой функционал

При клике выбирается чек- бокс. Важный вопрос, как сделать проверку что если хотя бы один чек бокс из пунктов выбрано - то parent должен иметь класс active введите сюда описание изображения

0

3 ответа 3

4

Вот простой пример как ето можно сделать :

document.querySelectorAll('input[type="checkbox"]').forEach(cb => cb.addEventListener('change', e => {
  const countChecked = document.querySelectorAll('input[type="checkbox"]:checked').length;
  e.target.closest('.parent').classList.toggle('active', countChecked);
}));
.active {
  background-color: lightblue;
}
<div class="parent">
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
  <input type="checkbox" />
</div>

3

Получить кол-во выбранных элементов:

var count = $(':checkbox:checked').length;

Потом проверяешь на если не 0, делаешь свои действия.

1

    const parent = document.querySelector('#parent')

    parent.addEventListener('click', (e) => {
        const inputChecked = this.document.querySelector('input:checked')
        parent.classList.contains('active') && parent.classList.remove('active');
        !!inputChecked && parent.classList.add('active');
    })
#parent {
  display: inline-block;
  padding: 1em;
}
#parent.active {
  background-color: gainsboro;
}
<div id="parent">

    <label for="checkbox_1">
        <input id="checkbox_1" type="checkbox" /> 1
    </label>

    <label for="checkbox_2">
        <input id="checkbox_2" type="checkbox" /> 2
    </label>

    <label for="checkbox_3">
        <input id="checkbox_3" type="checkbox" /> 3
    </label>

    <label for="checkbox_4">
        <input id="checkbox_4" type="checkbox" /> 4
    </label>

</div>

Так без цикла

<div id="parent">

    <label for="checkbox_1">
        <input id="checkbox_1" type="checkbox" /> 1
    </label>

    <label for="checkbox_2">
        <input id="checkbox_2" type="checkbox" /> 2
    </label>

    <label for="checkbox_3">
        <input id="checkbox_3" type="checkbox" /> 3
    </label>

    <label for="checkbox_4">
        <input id="checkbox_4" type="checkbox" /> 4
    </label>

</div>

<script>

    const parent = document.querySelector('#parent')

    parent.addEventListener('click', (e) => {
        const inputChecked = this.document.querySelector('input:checked')
        parent.classList.contains('active') && parent.classList.remove('active');
        !!inputChecked && parent.classList.add('active');
    })

</script>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.