Skip to content
Advertisement

How to separately validate each simple HTML radio form, created through a PHP loop, using Javascript and Jquery

I made a number of html forms containing only radio buttons and a submit button. However, I cannot get them to validate properly–independently of each other. Here is my code:

PHP/HTML code for the form:

<table>
<?php
for($i=0; $i<count($array1); $i++)
{
  $number = $i + 1;
  echo "<TR><TD>;
  echo "<form name='move' action='listChange_controller.php' method='POST'>Title:<br/>
        <input type='radio' name='change".$number."' value = 'val1' />Thing1
        <input type='radio' name='change".$number."' value = 'val2'/>Thing2
        <input type='radio' name='change".$number."' value = 'val3'/>Thing3
        <input type='button' name='submit' value='submit' onClick='validate(".$number.");'/>";
  echo "</form>";
  echo "</TD></TR>";
}
?>
</table>

Here is the javascript/jquery I have been trying, but has not worked:

function validate(number)
{
    var name_var = 'change'+number;
    if($('input:radio[name=name_var]:checked').length > 0)
    {
        $.post('file.php',{ name_var:$('input:radio[name=name_var]:checked').val()});
    }
    else
    {
       alert('You must choose');
       return false; 
    }
}

When I do this, it always thinks I have not chosen a radio button before pressing submit; it always carries out the ‘else’ part of my javascript function.

Please let me know why it is not working, and what would work. Any help and suggestions appreciated.

Advertisement

Answer

This line…

if($('input:radio[name=name_var]:checked').length > 0)

should read

if($('input:radio[name=' + name_var + ']:checked').length > 0)
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement