0

Есть пустой массив (var arr = [];).

Есть множество checkbox'ов с одинаковым классом (можно перебирать через цикл).

Вопрос: как сделать, чтобы если checkbox активный, то он добавляется в массив; если нет - он удаляется из массива. Мне важно, чтобы arr.length === количество активных checkbox'ов. События происходит при клике на checkbox'ы.

Вот код, который следит за изменением. Но тут немного другой функционал.

$( 'input.sl-chb' ).on( 'click', function() {
  $( '#cityList' ).html( $('input:checked' ).val() );
  if(TextCity.innerHTML == 'Был выбран undefined'){
    TextCity.innerHTML = 'Выберите город';
  }
});

Тут отображается только один. Мне нужен массив для того, чтобы делать условия, мол если длина массива больше двух, то .html('Выбрано городов : ' + arr.length;)

2 ответа 2

3

что-то такое ?

$('input.sl-chb').on('click', function() {
  $('#cityList').html($('input.sl-chb:checked').length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />
<input type="checkbox" class="sl-chb" />

<div id="cityList"></div>

Ваш массив, в данном случае, это $('input.sl-chb:checked'), то есть просто выборка всех input:checked.

1

А как вам такое на "ваниле"?

var arr = [];
var checkboxs = document.querySelectorAll('.sl-chb');

checkboxs.forEach(checkbox => {
  checkbox.onclick = () => {
    var elems = document.querySelectorAll('.sl-chb:checked');
    var arr = [].map.call(elems, function(obj) {
      return obj.value;
    });
    console.log(arr);
  }
})
<label><input type="checkbox" class="sl-chb" value='oдин' />один</label><br>
<label><input type="checkbox" class="sl-chb" value='два' />два</label><br>
<label><input type="checkbox" class="sl-chb" value='три' />три</label><br>
<label><input type="checkbox" class="sl-chb" value='черыре' />черыре</label><br>
<label><input type="checkbox" class="sl-chb" value='пять' />пять</label><br>
<label><input type="checkbox" class="sl-chb" value='шесть' />шесть</label><br>

1
  • 1
    Неплохо, неплохо... +1
    – Yuri
    6 авг 2017 в 18:43

Ваш ответ

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

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