简体   繁体   中英

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); } }

* Moved from the comment to answer section.

Add the required attribute to all input tags.

eg:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM