我现在的写法是,比如表单有10个文本框
js:if(text1 == '') {
    alert("text1不能为空");
    return;
}
if(text2 == '') {
    alert("text2不能为空");
    return;
}
if(text1 == '') 
.............现在是这样写的,有没有更好的做法

解决方案 »

  1.   

    参考
    for (var i = 1; i <= 10; i++) {
        var name = "text" + i;
        var element = document.getElementById(name) || document.getElementsByName(name)[0];
        if (!element) continue;
        if (!element.value) {
            alert(name + "不能为空");
            return;
        }
    }/* TODO : 提交 */
      

  2.   

    用正则验证吧~!
    for (var i = 1; i <= 10; i++) {
        var name = document.getElementsByName("XXXXXXX");
        var element = /^\w+$/;
        if (!element.test(name[i].value)) {
            alert(name[i]+ "不能为空");
            return;
        }
    }
      

  3.   

    不对 应该提出来:var element = /^\w+$/;
     var name = document.getElementsByName("XXXXXXX");
    for (var i = 1; i <= name.length; i++) {
      if (!element.test(name[i].value)) {
      alert(name[i]+ "不能为空");
      return;
      }
    }
      

  4.   

    text1/test2这只是一个示例,真实环境不可能用这种名字
      

  5.   

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>无标题页</title>
        <script type="text/javascript">
            function Judge(){
                var item = document.body.getElementsByTagName("input");
                for(var i=0;i<item.length;i++){
                    if(item[i].type=="text"){
                        if(item[i].value==""){
                            alert(item[i].getAttribute("title")+"不可以为空!");
                        }
                    }
                }
                
            }
        </script>
    </head>
    <body>
        <input id="File1" type="file" />
        <input id="UserName" title="用户名" type="text" />
        <input id="Password" title="密码" type="text" />
        <input id="ID" title="ID" type="text" />
        <input id="Age" title="年龄" type="text" />
        <input id="Button1" type="button" value="button" onclick="Judge()" />
    </body>
    </html>
      

  6.   

    一般只做服务器端的验证,然后前台用ajax提交懒得服务器端写一次验证,客户端再写一次验证了
      

  7.   

    用jquery 来验证比较好。 <script type="text/javascript">
            $(function() {
                $("#btnSubmit").click(function() {
                    //遍历所有的txtbox
                    $("input[type='text']").each(function() {
                        if ($(this).val().length == 0) {
                            alert('不能为空');
                        }                })
                })        })
        </script>