Sharmae Reyes
Sharmae Reyes

Reputation: 115

How to validate dynamic radio button from PHP

How to validate radio button if at least one in the question is not answered. If you wondered I use while loop in html to display all the questions. I'm trying the server side validation because I have no idea on how to validate in Javascript.

Sample Question Output Do you have a fever or temperature over 38 °C? * Yes No --other questions here

<div class="form-group">
  <label for="" name="qid[<?php echo $row['id'] ?>]"><?=$row['questions']?> *</label>
  <div class="form-check">
    <input class="form-check-input" type="radio" name="ans[<?php echo $row['id'] ?>" value="Yes">
    <label class="form-check-label">Yes</label>
  </div>
  <div class="form-check">
    <input class="form-check-input" type="radio" name="ans[<?php echo $row['id'] ?>" value="No">
    <label class="form-check-label" value="No">No</label>
  </div>
</div>

foreach($_POST as $key => $val)
{
  if(substr($key, 0, 3) == 'ans')
  {
      $key = substr($key,4);
      // $sql2 = "INSERT INTO health_declaration (patient_id,question_id,answer) VALUES ('$patient_id','$key','$val') ";
      // $query_run1 = mysqli_query($conn,$sql2);
  }
}

Upvotes: 4

Views: 92

Answers (1)

amlxv
amlxv

Reputation: 2005

* Moved from the comment to answer section.

Add the required attribute to all input tags.

e.g:

<input type="radio" ... required>

https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required

Upvotes: 2

Related Questions