简体   繁体   中英

How to validate loop dynamic radio button?

I'm developing some questionnaire for user to answer. Using loop radio button, here's my code:

<?php
  $i4 = 1;
  while ($rows_element4 = mysql_fetch_array($result_element4)){
  ?>
  <tr>
  <td><?php echo $i4; ?></td>
  <td><?php echo $rows_element4['question_bm']; ?><br/><br/><i><?php echo $rows_element4['question_bi']; ?></i></td>
  <td><input type="radio" name="e4q<?php echo $i4; ?>" id="e4q<?php echo $i4; ?>" value="1" required oninvalid="this.setCustomValidity('Please choose something')"></td>
  <td><input type="radio" name="e4q<?php echo $i4; ?>" id="e4q<?php echo $i4; ?>" value="2"></td>
  <td><input type="radio" name="e4q<?php echo $i4; ?>" id="e4q<?php echo $i4; ?>" value="3"></td>
  <td><input type="radio" name="e4q<?php echo $i4; ?>" id="e4q<?php echo $i4; ?>" value="4"></td>
  <td><input type="radio" name="e4q<?php echo $i4; ?>" id="e4q<?php echo $i4; ?>" value="5"></td>
  </tr>
  <?php
  $i4++;
  }
  ?>

I'm not familiar with javascript / jquery. How to validate radio button in this form so that all questions will not left blank.?

You can create a simple function which will check if any radio button is not checked it will return false.

function isSubmissionValid(){
var isValid = true;
     if (!$("input[name='e4q']:checked").val()) {
        isValid = false;
      }
return isValid;
}

Now on submit button click call this function which will let you examine if any radio button is left unchecked.

 $('#submit_button').click(function() {
    if(isSubmissionValid())
    {
        //go ahead with form submission
    }
    else
    {
       alert("You must select all answer");
    }
 });

Edit

You can use input[name^='e4q'] which will select all your radio starting with e4q.

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