dimanche 22 avril 2018

Trying to limit the number of checkboxes that can be checked using javascript

Let me start by saying other questions similar to this had jquery responses and I'm trying to use only javascript. I'm trying to limit the number of checkboxes that can be checked at one time in this code. In my javascript code I'm seeing my 'checkedcount' variable increments only 1 time. For example I have 5 checkboxes available it should increment to 5 if all checkboxes are checked. It's only incrementing to 1 though, from what I'm seeing.

var showSpan = function(){
        var option = this,
                option_value = option.value;
      spanID = document.getElementById(option_value),
      spanID_value = spanID.id;
      
      if (option.checked){
        if (option_value === spanID_value) spanID.textContent = "Display text";
      } else {
        spanID.textContent = "";
      }
};

var checkLimit = function(){
        var option = this,
                option_value = option.value,
      checkedcount = 0,
      maxChecked = 2;
      
      if (option.checked) {
        checkedcount += 1;
        console.log(checkedcount);
      }
};


var elements = document.getElementsByClassName('display');
var e = new Event('change');

for ( var i=0, len=elements.length; i<len; i++ ){
        var element = elements[i];
  element.addEventListener('change', showSpan);
  element.addEventListener('change', checkLimit);
  element.dispatchEvent(e);
}
<input type="checkbox" name="1" class="display" value="1"> 1 <span id="1"></span>
<br>
<input type="checkbox" name="2" class="display" value="2"> 2 <span id="2"></span>
<br>
<input type="checkbox" name="3" class="display" value="3"> 3 <span id="3"></span>
<br>
<input type="checkbox" name="4" class="display" value="4"> 4 <span id="4"></span>
<br>
<input type="checkbox" name="5" class="display" value="5"> 5 <span id="5"></span>

JSFiddle




Aucun commentaire:

Enregistrer un commentaire