There is an empty array ( var arr = []; ).

There are many checkboxes with the same class (you can cycle through the loop).

Question: how to make that if checkbox is active, then it is added to the array; if not, it is removed from the array. It is important to arr.length === количество активных checkbox'ов that arr.length === количество активных checkbox'ов . Events occur when you click on checkboxes.

Here is the code that keeps track of the change. But there is a slightly different functionality.

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

Only one is displayed here. I need an array in order to make the conditions, they say if the length of the array is more than two, then .html('Выбрано городов : ' + arr.length;)

    2 answers 2

    Something like this ?

     $('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> 

    Your array, in this case, is $('input.sl-chb:checked') , that is, just a sample of all input:checked .

      And how do you like this on "vanilla"?

       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> 

      • one
        Not bad, not bad ... +1 - Yuri