使用Javascript验证表单

时间:2010-10-26 15:09:13

标签: javascript html

我正在尝试使用Javascript进行验证过程,我的表单有四个单选按钮和一个提交按钮,我想这样做,如果用户点击提交并且没有选择单选按钮,那么它会弹出一个提醒并不提交表格。这是我的表单的样子:

<form method="post" name="inform">
If you checked off <span style="text-decoration:underline">any</span> problems, how  <span style="text-decoration:underline">difficult</span> have these problems made it for you to do your work take care of things at home or get along with other people?
<table id="lastquestion">
<tr>
<td>Not difficult at all</td>
<td>Somewhat difficult</td>
<td>Very difficult</td>
<td>Extremely Difficult</td>
</tr><tr>
<td style="text-align:center"><input type="radio" value="not difficult at all" name="finalquestion" /></td>
<td style="text-align:center"><input type="radio" value="somewhat difficult" name="finalquestion" /></td>
<td style="text-align:center"><input type="radio" value="very difficult" name="finalquestion" /></td>
<td style="text-align:center"><input type="radio" value="extremely difficult" name="finalquestion" /></td>
</tr>
</table>
<input type="hidden" value="<?php echo $totalScore; ?>" name="totalScore" />
<input type="submit" value="Submit Final Answer" name="submit" onclick="return validate(inform)" />
</form>

以下是脚本的样子:

function validate(formCheck)
{
    if(formCheck.finalquestion == "")
    {
        alert("Please Choose an option");
        return false;
    }
    else
    {
        return true;
    }
}

但由于某些原因我的按钮无论如何都在提交,这里的任何建议都会有所帮助,谢谢!

更新:我尝试选择一个收音机,然后在验证功能和formCheck.finalquestion中发出警告:[object NodeList],所以我不认为选择哪个按钮的值是正确的。

1 个答案:

答案 0 :(得分:2)

您依赖于仅在IE中有效的命名行为:只有该浏览器为每个元素{{1}提供全局Javascript变量xyz(或更确切地说,window.xyz) }}。

要指定表单,请使用提交按钮的name属性。它始终是对表单对象的引用:

form

要获取单选按钮的元素,您需要指定return validate(this.form); 属性。使用

value