SeleM
SeleM

Reputation: 9678

Wrong behavior while checking radio buttons in a Loop (using Angular2)

I'm working on an Angular2 project & currently i'm stuck with a Quizz module, so illustrating the problem ; when a candidate wants to pass a test he will get that test with some questions ; every question has 4 propositions with radio buttons and he should answer merely by checking one of them for every question. here is the HTML snippet of what i'm talking about :

 <div *ngFor="#qt of listQuestion">

<h3 class="uk-accordion-title" >{{qt.wordingQ}}</h3>

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

          <input type="radio" id="radio_demo_1"  />

          <label for="radio_demo_1"> <b>{{qt.lpo[0]}}</b></label> <br><br>

          <input type="radio" id="radio_demo_2"  />

          <label for="radio_demo_2"><b>{{qt.lpo[1]}}</b></label><br><br>

          <input type="radio" id="radio_demo_3"   />

          <label for="radio_demo_3"> <b>{{qt.lpo[2]}}</b></label> <br><br>

          <input type="radio" id="radio_demo_4" />

          <label for="radio_demo_4"><b>{{qt.lpo[3]}}</b></label>


                                   </div> </div>

Where the listQuestion is a list of Question entities which each one of them has a wording and a list of propositions (lpo), in that way i cannot check only one radio button for every question as it is shown below : enter image description here I tried to remove the id in the <input> tags and it still the same problem , I've changed the id by name and give the same name for all tags thus, I could check only one proposition but when moving to another question and checking a new proposition , the first one will be cleared. Any help Please ?

Upvotes: 0

Views: 471

Answers (1)

Dmitriy Khudorozhkov
Dmitriy Khudorozhkov

Reputation: 1623

Your problem is that the way you currently do it, you have a single radio group for all questions. You can solve it by creating radio element name attributes dynamically. Something like this:

<h3 class="uk-accordion-title" >{{qt.id}}</h3>

      <input type="radio" id="radio_demo_{{qt.id}}_{{index$}}" name="radio_demo_{{qt.id}}_{{index$}}" />

      <label for="radio_demo_{{qt.id}}_{{index$}}"> <b>{{qt.lpo[0]}}</b></label> <br><br>

{{qt.id}} (or any other qt property that uniquely identifies the question) is the key here.

This way, you'll have a separate radio group for each question, because group names won't intersect.

Upvotes: 1

Related Questions