首次使用DOM来改变表单onSubmit中未答复问题的颜色

时间:2012-07-11 10:26:08

标签: javascript dom getelementbyid

这是我的表格:

<form id="Test" action="index.php?course=4" method="post" name="Test" onSubmit="IsFormComplete(12)">  

表单内部是一个动态生成的表,其中id = Qx class = Qx,其中x是1到12:

 <tr id="Q2" class="Q2">  
            <td width="5%">2) </td>  
            <td colspan="2">According to the Institute of Medicine study the number of deaths from medical errors per year is between</td>  

这是我的javascript函数:

function IsFormComplete(iQuestions) {  
var questionNum = iQuestions;  
    itemOkay=true;  
    for (var i=1;i<questionNum;i++) {  
        for (var j=0;j<4;j++) {  
            var thisItem = eval("document.Test.Q" + i + "[" + j + "].checked");  
            if (!thisItem)  {  
                itemOkay = false;  
                document.getElementById(eval("Q" + i)).style.color = "red";  
            }  
        }  
    }  
    alert("item okay = " + itemOkay);  
    if (itemOkay) {  
        return true;  
    } else {  
        return false;  
    }  

}

不工作请帮忙。 DOM新手并尝试了各种标签:

document.getElementById(eval("Q" + i)).style.color = "red";  
document.Test.getElementById(eval("Q" + i)).style.color = "red";  
document.getElementById("Q1").style.color = "red";  //To try literal instead of variable

1 个答案:

答案 0 :(得分:3)

您不需要eval。 getElementById使用字符串。试试这个:

document.getElementById("Q"+i).style.color = "red";