javascript - 使用 Javascript 验证表单

标签 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;
    }
}

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

更新:我尝试选择一个 radio ,然后在验证函数中发出警报,并且 formCheck.finalquestion 打印:[object NodeList],所以我认为选择的按钮的值没有正确通过。

最佳答案

您所依赖的命名行为仅适用于 IE:只有该浏览器提供全局 Javascript 变量 xyz(或更准确地说,window.xyz)对于具有该名称的每个元素。

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

return validate(this.form);

要获取单选按钮的元素,您需要指定value属性。使用

if(formCheck.elements.finalquestion.value == "")

关于javascript - 使用 Javascript 验证表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4025052/

相关文章:

javascript - PHP 比较两个日期

javascript - AngularJS 不解析对象数组

javascript - 使用 Web api 并获取引用错误

javascript - 使用 jQuery 或 Mootools 显示 Rokbox 弹出窗口

javascript - 运算符 OR 解析为 false?

javascript - call/CC 关闭

php - 提交表单前修改html : prevent this hack

html - 如何使用 css 创建虚线网格/图表表背景?

javascript - 使用 HTML DOM .createElement()、.setAttributeNode() 和 .appendChild() 方法时遇到困难

javascript - AngularJS - 在 ng-init=true 时触发一个函数