Skip to content
Advertisement

Jquery use value of for loop to append to id attribute

I am making quiz like app. For every question, it will have 4 answers. Then I will use radio buttons to indicate the right answer. How can I append the value of the loop to the id attribute?

Thank youuu

Here is my code snippet:

  $('#num_qu').on('change', function(){
    var num_of_qu = $('#num_qu').val();
    var html = "";

    for (var i = 0; i < num_of_qu; i++){
        html+= '<div class="row"><div class="form-row"><div class="form-group col-md-6"> 
       <label>Name of question</label><input type="text" class="form-control" name="qu_name" 
         required></div></div></div>';
        for (j = 1; j < 5; j++){//4 answers
            <div class="row">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <input type="text" class="form-control" id=answer_j placeholder="Answer" 
                        required>
                    </div>
                </div>
            </div>

        }    
    }

Advertisement

Answer

As per our discussion, this answer works out for your needs:

$("#num_qu").on("change", function () {
  var num_of_qu = $("#num_qu").val();
  var html = "";

  for (var i = 0; i < num_of_qu; i++) {
    html += `<div class="row"><div class="form-row"><div class="form-group col-md-6"> 
       <label>Name of question</label><input type="text" class="form-control" name="qu_name" 
         required></div></div></div>`;

    for (j = 1; j < 5; j++) {
      //4 questions
      html += `<div class="row">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <input type="text" class="form-control" id=answer_${j} placeholder="Answer" 
                        required>
                    </div>
                </div>
            </div>`;
    }
  }
});

I just use template strings to place the value of j at the id attribute of the text input.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement