代码之家  ›  专栏  ›  技术社区  ›  Doug Molineux

用javascript验证表单

  •  0
  • Doug Molineux  · 技术社区  · 16 年前

    我正试图让验证过程使用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;
        }
    }
    

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

    更新:我试过选择一个收音机,然后在validate函数和formcheck中发出警报。最后一个问题打印出来了:【对象节点列表】,所以我认为选择哪个按钮的值不会正确通过。

    1 回复  |  直到 16 年前
        1
  •  2
  •   Pekka    16 年前

    您依赖于仅在IE中工作的命名行为:只有浏览器提供了一个全局javascript变量 xyz (或者更确切地说, window.xyz )对于每个元素 name 。

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

    return validate(this.form);
    

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

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