Client-side validation for radio buttons in php
<p>I'm trying to create a form with multiple radio buttons. I'm generating radio buttons using a for loop like so:</p>

<pre><code>&lt;form name="myForm" method="POST" id="myForm" action="result.php" onsubmit=""&gt;
&lt;?php for ($i = 1; $i &lt;= $row = mysqli_fetch_array($result); $i++)
{ ?&gt;
    &lt;input type="radio" name="opt&lt;?php echo $i; ?&gt;" id="opt&lt;?php echo $i; ?&gt;" value="A"/&gt;&lt;br/&gt;
            &lt;input type="radio" name="opt&lt;?php echo $i; ?&gt;" id="opt&lt;?php echo $i; ?&gt;" value="B"/&gt; &lt;?php } ?&gt;
</code></pre>

<p>I want to make sure that for each radio button group, there is 1 selected answer. I've been searching endlessly and I've come up with this code:</p>

<pre><code>&lt;/script&gt;&lt;script type="text/javascript"&gt;
function validate() {
var x = "&lt;?php echo $j;?&gt;";

var formValid = false;
for (var i = 1; i &lt;= x; i++)
{
    var y = document.getElementsByName("opt"+i);        
    var j = 0;
    while (!formValid &amp;&amp; j &lt; y.length){
        if (y[j].checked) {
            formValid = true;
            j++;
            alert("test");
        }
        break;
    }   
}

if (!formValid) { alert("all fields required");
    return false;
}
else
{
    var form = document.getElementById("myForm");
    form.submit();
}&lt;/script&gt;
</code></pre>

<p>My problem with this is even if all the radio buttons have been ticked, all fields required still pops up and the form would submit. Is there something I'm missing here? Please help. I've been stuck with this for days. </p>
