简体   繁体   中英

Client-side validation for radio buttons in php

I'm trying to create a form with multiple radio buttons. I'm generating radio buttons using a for loop like so:

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

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:

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

var formValid = false;
for (var i = 1; i <= x; i++)
{
    var y = document.getElementsByName("opt"+i);        
    var j = 0;
    while (!formValid && j < 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();
}</script>

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.

Once you've found once checked field, you're never checking the rest, assuming all is well.

You want to check the fields individually, bailing when you see one that isn't valid.

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

    if (! fieldValid)
    {
      formValid = false;
      break;
    }
}

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