jeudi 26 juillet 2018

Vanilla JS: Loop through checkboxes and conditionally disable unchecked

I'm trying to write a basic function in pure JS that simply checks the number of checked checkboxes, and if that number exceeds a certain amount, disables the rest. I can achieve this easily in jQuery, but trying to get it working in pure JS. I have a CodePen set up here and I'm including my working JS below. Thanks for any insight here.

(function() {

  var checkboxes = document.querySelectorAll('input[id^="mktoCheckbox"]');
  var active = document.querySelectorAll('input[id^="mktoCheckbox"]:checked');
  var numActive = active.length;

  console.log(numActive);

  if (numActive > 1) {
    for(var i = 0; i < checkboxes.length; i++){
            if (checkboxes[i].checked == true) {
                return;
            } else {
                checkboxes[i].disabled == true;
            }
        }
  }

})();




Aucun commentaire:

Enregistrer un commentaire