form = window.document.forms[0];        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i].type = "text") {
                alert("2");
                form.elements[i].value = "helloworld";
            }        }
    
    </script>
    <title></title>
</head>
<body>
    <form runat="server">
    <input type="button" id="opw" onclick="openwindows()" value="打开" />
    <input type="button" id="clw" onclick="closewindows()" value="关闭" />
    <input type="text" name="tx1" id="tx1" />
    <input type="text" name="tx2" id="tx2" />
    </form>
</body>
</html>
刚学JS这为什么会报错 提示form is undefinde

解决方案 »

  1.   

    HTML源码是从上往下一行一行执行的,你在HEAD部分执行JS脚本的时候form还没有装载,当然“form is undefinde”,你把JS代码快放在form后面,或者把JS代码放在一个函数中:window.onload=function(){你的JS代码},试试看。
      

  2.   

    js 放html 下面
    或者把js 写到 onload 中获取 input 用 getElementsByTagName("input")
      

  3.   

    1. form定义时不建议这样:<form runat="server">   最好使用:<form id="加上Form的ID" runat="server">
    2. 在获取form时不建议这样:window.document.forms[0]
     
       最好使用:document.getElementById('Form的ID').....