这肯定是简单的(我希望)我忽略的事情。我有一组 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;
}
}
}
最佳答案
1,for 循环中的第二个参数不正确
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>
关于Javascript 和单选按钮 - 不执行任何操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19799239/