jeudi 16 juin 2016

Check only one checkbox (radio buttons behavior) within an *ngFor loop

I have a Quizz module developed in Angular2, so merely some questions with proposed answers and you have to check only one answer , I know radio buttons can handle the situation but i want it to be checkboxes with a radio button behavior, the issue is that i did a part of the job but since it is more complicated within an *ngFor loop , once i check a B-Question answer the A-Question checked answer will be unchecked and so on. Here is my HTML :

<div *ngFor="#qt of listQuestion"><h3 class="uk-accordion-title" ></h3>

           <div class="uk-accordion-content">

    <input type="checkbox" class="cb"  id="0" [(ngModel)]="qt.chp[0]" onchange="cbChange(this)" />

    <label for="0" class="inline-label" > <b></b></label><br><br>

    <input type="checkbox" class="cb"   id="1" [(ngModel)]="qt.chp[1]" onchange="cbChange(this)" />

    <label for="1" class="inline-label"><b></b></label><br><br>

    <input type="checkbox" class="cb"   id="2" [(ngModel)]="qt.chp[2]" onchange="cbChange(this)"/>

    <label for="2" class="inline-label"> <b></b></label><br><br>

    <input type="checkbox" class="cb"  id="3" [(ngModel)]="qt.chp[3]" onchange="cbChange(this)"/>

    <label for="3" class="inline-label"><b></b></label>

                               </div></div>

And here is the Script making the solo-checking way :

<script>
  function cbChange(obj) {
    var cbs = document.getElementsByClassName("cb");
    for (var i = 0; i < cbs.length; i++) {
      cbs[i].checked = false;
    }
    obj.checked = true;
  }
</script>

As you can see it is an *ngFor loop to load a list of questions ; every question has a list of propositions (lpo[i]) and the [(ngModel)]="qt.chp[i]" is for taking the status of every proposition (checked proposition) , I think i have to refer every onchange function to every unique ngModel (as it is in indexing) but i do not know how. Any help Please ? (Here is a real image of the situation)

enter image description here




Aucun commentaire:

Enregistrer un commentaire