mardi 18 juillet 2017

Limit Checkbox checked count to 5

I have 20 checkboxes I need to be able to limit the amount of checked checkboxes to 5/20. Based on the checked checkbox it should hide/show the label.

Upon checking 5, no more should be checked, and upon unchecking 5 or any subsequent, it should allow me to check a different box up to the limit again of 5.

My Checkboxes are generated using the angular directive *ngFor, and by there will be 5 answers therefore 5 checks to begin with.

      <div *ngFor="let question of questions; let i = index" class="row container-generic">
    <div class="col-md-8">
      <div class="container-input-checkbox">
        <label class="container-flex">
          <input #checkBox class="pvq-create-checkbox" type="checkbox" name="" (change)="checkedState($event, checkBox)" [checked]="question.answer"> 
          <div class="pvq-create-label">
            <div *ngIf="lang == 'en'">
               <p></p>
            </div>
            <div *ngIf="lang == 'fr'">
               <p></p>
            </div>
          </div>
        </label>
        <label [@hideShow]="checkBox.checked ? 'show' : 'hide'" >Answer
          <input type="textbox" name="" placeholder="">
        </label>
      </div>
    </div>
  </div>

In my component I have tried everything, when I try to disable the checkboxes after the 5th, it does not allow me to uncheck or re-check because it is disabled at a count of 5. Can no longer change the state of the checkbox, is this possible?

      checked(checkBox) {
    let index = checkBox.name;
    console.log('Index from checked() --> {}', index);
    if(this.answers[index] != "" && this.createMode){
      return true;
    }
      //For Example it will always pass through here updateMode = true
    if(this.answers[index] != "" && this.updateMode ){
      return true;
    }
  }

  checkedState(event, checkBox){
    let index: number = event.target.name;
    console.log('Index is ' + index);
    if(event.target.checked && this.counter < 4 && this.updateMode){
      this.counter++;
      console.log('checked ' + this.counter);
      this.checked(checkBox);

    } 

    if(!event.target.checked && this.counter != 0 && this.counter <= 5 && this.updateMode){
      --this.counter;
      console.log('unchecked ' + this.counter);
    }
  }

  hideShow(){
    return 'hide';
      // return 'show';
  }




Aucun commentaire:

Enregistrer un commentaire