0

This is the code for the php file containing the form with radio buttons:

<?php
    while($r7 = mysql_fetch_array($rt3)){
        $name=$r7["name"];  
        $s=$r7["question"]; 

        echo "
        <div>$s</div>

        <form name='Tester' method='post' onSubmit='return RegValidate(this);' action='quest.php' >
        <input type='radio' name='w1' value='1'>1<br>
        <input type='radio' name='w1' value='2'>2<br>
        <input type='radio' name='w1' value='3'>3<br>



        ";
        }
        echo" <input  name='Submit' value='Tester' type='submit' />
        </form>";

?>

The $name and $q are derived from the database using a mysql query. This works fine. I have used the following javascript code so far:

function RegValidate(Tester) 
 {

 if($('#w1').not(':checked'))
{
   alert('Radio not checked');
   return false;
}

}

But with this code, I continue to get the error message, and I am not able to move on even though I have selected a radio button.

The while loop produces several sets of radio buttons, as $q, gets the question from the database and posts it on the page along with 3 radio buttons. Each question $q, has the 3 radio buttons in the above, hence the reason for the $name.

How do I validate this form with javascript. NB. The form will only contain radio buttons.

user1704514
  • 227
  • 3
  • 4
  • 12

3 Answers3

0

you have an error, your input doesn't have ID or CLASS, so add to all of the input radio class='w1' and try the next code:

 if ($(".w1 option:selected").length<1)
     alert ('nothing selected');

also take a look to this post: Check if option is selected with jQuery, if not select a default

Community
  • 1
  • 1
jcho360
  • 3,724
  • 1
  • 15
  • 24
0

do these things:

      <input type='radio' class='w1' name='w1' value='1'>1<br>
      <input type='radio' class='w1' name='w1' value='2'>2<br>
      <input type='radio' class='w1' name='w1' value='3'>3<br>

And in js:

Latest edit:

  if ( $(':radio[class=w1]').attr('checked') != 'checked' ) {
    alert('Radio not checked');

}
Teena Thomas
  • 5,139
  • 1
  • 13
  • 17
  • I am sorry, but this doesnt seem to fix it. I think it might be because the form is in a php while loop. I really don't know how to fix this. – user1704514 Sep 27 '12 at 21:03
  • This still gives the same problem. The error messages keep coming up even though I have selected. The while loop produces several sets of radio buttons, as $q, gets the question from the database and posts it on the page along with 3 radio buttons. – user1704514 Sep 27 '12 at 21:53
0
function RegValidate(Tester) {
    if ($(":radio[name=w1]:checked").toArray().length == 0) {
        alert('nothing selected');
        return false;
    }
}​

FIDDLE

Barmar
  • 741,623
  • 53
  • 500
  • 612