开发者

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

开发者 https://www.devze.com 2023-03-25 21:10 出处:网络
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:

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>";
开发者_C百科}
?>
</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.


This line...

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

should read

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


Change...

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

to...

if ($('input[name=' + name_var + ']').is(':checked'))
0

精彩评论

暂无评论...
验证码 换一张
取 消