javascript - Client-side validation for radio buttons in php -


i'm trying create form multiple radio buttons. i'm generating radio buttons using loop so:

<form name="myform" method="post" id="myform" action="result.php" onsubmit=""> <?php ($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 make sure each radio button group, there 1 selected answer. i've been searching endlessly , i've come code:

</script><script type="text/javascript"> function validate() { var x = "<?php echo $j;?>";  var formvalid = false; (var = 1; <= 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 if radio buttons have been ticked, fields required still pops , form submit. there i'm missing here? please help. i've been stuck days.

once you've found once checked field, you're never checking rest, assuming well.

you want check fields individually, bailing when see 1 isn't valid.

var formvalid = true; (var = 1; <= 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;     } } 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -