Z
Z
zhigunov132021-06-14 18:53:14
JavaScript
zhigunov13, 2021-06-14 18:53:14

How to count the number of checked and display the result?

Task: make it so that "__select__title" displays the number of checkboxes with the value "checked", and if nothing is selected, then display "Select from the list ..."

Probably, the count of checkboxes with the value "checked" can be done using

var checked = $(target).find("input[type='checkbox']:checked").length;

but for some reason I can't.

Source:
<form>
  <div class="__select" data-state="">
  <div class="__select__title"></div>
  <div class="__select__content">
  <input id="singleSelect1" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect1" class="__select__label">Option 1</label>
  <input id="singleSelect2" class="__select__input" type="checkbox" name="singleSelect" disabled />
  <label for="singleSelect2" class="__select__label">Option 2 (disabled)</label>
  <input id="singleSelect3" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect3" class="__select__label">Option 3</label>
  <input id="singleSelect4" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect4" class="__select__label">Option 4</label>
  <input id="singleSelect5" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect5" class="__select__label">Option 5</label>
  <input id="singleSelect6" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect6" class="__select__label">Option 6</label>
  <input id="singleSelect7" class="__select__input" type="checkbox" name="singleSelect" />
  <label for="singleSelect7" class="__select__label">Option 7</label>
  </div>
  </div>
</form>

JS:
const selectSingle = document.querySelector('.__select');
const selectSingle_title = selectSingle.querySelector('.__select__title');
const selectSingle_labels = selectSingle.querySelectorAll('.__select__label');

selectSingle_title.addEventListener('click', () => {
  if ('active' === selectSingle.getAttribute('data-state')) {
  selectSingle.setAttribute('data-state', '');
  } else {
  selectSingle.setAttribute('data-state', 'active');
  }
});

Help me please!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Spartak (Web-StyleStudio), 2021-06-14
@Spartak-2205

var checked = 0;

$(document).ready(function() {
  $("form").on("change", "input.__select__input", function() {
    checked = $("input.__select__input[type='checkbox']:checked").length;
    $(".__select__title").html(checked > 0 ? checked : "Выберите из списка...");
  });
  $(".__select__title").html(checked > 0 ? checked : "Выберите из списка...");
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question