Javascript和单选按钮 - 没有做任何事情

时间:2013-11-05 21:21:59

标签: javascript php

这个一定是简单的(我希望)我忽略的东西。我有一组50个问题,从表中提取并放入表格进行回答。我想检查以确保他们都得到了答案(必填)。当用户点击提交时,不会出现任何警告框(甚至是调试框)。我在这里错了什么?

首先,PHP:

     echo 'Please complete ALL 50 questions, then press the "SUBMIT" button at the bottom of the page.';
     $query = "SELECT * 
        FROM `starriskquestions` 
        ORDER BY `QuestionNum` ASC"; 
 $results = $pdo->query($query);
 echo '<form name="submitra" action="riskassessmenttest.php" onsubmit="return validateForm()" method="post">';
  while ($row = $results->fetch()) {
  echo '<br>' .$row["QuestionNum"] . ') ' . $row["Question"] . '<br>
            <input type="radio" name="a'.$row["QuestionNum"].'" value="1" /> Yes ---- 
            <input type="radio" name="a'.$row["QuestionNum"].'" value="-1" /> No<br><br>';
  } 
  echo "<br> ARE YOU SURE YOU ANSWERED ALL 50 QUESTIONS??? <br> If so, click the ";
  echo "submit buton below <br>";
  echo '<input type="hidden" name="testid" value="'.$testid.'">';
  echo '<input type="submit" name="submittestanswers" value="submit">';
  echo ' </form>';

然后是Javascript

    function validateForm()
{
    for (var answerloop=1; <=50; answerloop++)
    {
        var answernum = '"'+ "a" + answerloop + '"';
        alert (answerloop);
        var x=document.getElementByName(answernum).value;
        alert ("This is the variable X: " + x);

        if (x!=="1" || x!=="-1")
         {
            alert(" One or more questions must be filled out");
             return false;
         }
    }
}

3 个答案:

答案 0 :(得分:1)

我认为这是错误的:

for (var answerloop=1; <=50; answerloop++)

将其更改为:

for (var answerloop=1; answerloop <=50; answerloop++)

答案 1 :(得分:1)

1,for loop

中的第二个参数不正确

2,document.getElementByName()应为document.getElementsByName()

function validateForm(){
    for (var answerloop=1; answerloop<=50; answerloop++){
        var name = 'a' + answerloop;
        var names=document.getElementsByName(name);
        var is_checked = false;

        for(var i=0;i<names.length;i++){
            if(names[i].checked){
                is_checked = true;
            }
        }
        if(!is_checked){
            alert("One or more questions must be filled out");
            return false;
        }

    }
}

测试:

<form onsubmit="return validateForm()" method="post" action="./">
    <?php
    for($x=1;$x<=50;$x++){
        echo <<<EOD
        <input type="radio" name="a{$x}" value="1">
        <input type="radio" name="a{$x}" value="-1">
EOD;
    }?>
    <input type="submit" value="submit">
</form>

答案 2 :(得分:0)

第二个参数

中的for循环缺少answerloop
for (var answerloop=1; <=50; answerloop++)
                      ^ 

更改为

for (var answerloop=1; answerloop<=50; answerloop++)