1

I am using php to generate form questions:

<form action="formaction.php" method="post" name="form">

<?php
for ($j=0;$j<$no_of_ques;$j++)
switch ($qtype[$j]) { 
        case shorttext:
        echo " <textarea name='qno[$j]'></textarea>";
        break;
   case checkbox:

  for($l=0;$l<$no_of_choices;$l++) 
        { echo "<input type='checkbox' name='qno[$j]' value='$choices[$l]'>$choices[$l]";
        }
        break;
}
?>
<a href='#' class='submit button'onclick='myFunction()'>Submit</a>
<script>
 function myFunction(){ 
If (document.getElementsByName("qno").checked)
     document.forms['form'].submit(); 
     }
    </script>

This is obviously incorrect.I am using a styled anchor to submit the form with js. How must I use the js to validate if each question has been answered?

1 Answer 1

2

give them all the same classname and access them via getElementsByClassName. This way you can keep the name attribute like that.

<form action="formaction.php" method="post" name="form">

<?php
for ($j=0;$j<$no_of_ques;$j++)
switch ($qtype[$j]) { 
        case shorttext:
        echo " <textarea class="xxx" name='qno[$j]'></textarea>";
        break;
   case checkbox:

  for($l=0;$l<$no_of_choices;$l++) 
        { echo "<input class="xxx" type='checkbox' name='qno[$j]' value='$choices[$l]'>$choices[$l]";
        }
        break;
}
?>
<a href='#' class='submit button'onclick='myFunction()'>Submit</a>
<script>
 function myFunction(){ 
     var ok = true;
     for(obj in document.getElementsByClassName("xxx")) {
         if(!obj.checked) {
             ok = false;
             break;
         }
     }
     if(ok) {
        document.form.submit();
     }
}
</script>

sorry i am on my phone and cant test it :)

Sign up to request clarification or add additional context in comments.

2 Comments

I already have class names for styling. Can I use ID's instead? And what would the arguments be then?
take a look at it now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.