D.Joe
D.Joe

Reputation: 51

JavaScript document.getElementsByName() argument to match input name as array

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?

Upvotes: 1

Views: 137

Answers (1)

ave4496
ave4496

Reputation: 3018

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 :)

Upvotes: 2

Related Questions