2013-04-07 58 views
0

我有复选框和文本字段的html页面,并且JavaScript能够验证 复选框但不验证文本字段。谁能帮,因为我不知道它是错的验证文本字段不起作用

<html> 
    <head> 
    <script type="text/javascript"> 
    function validator() 
    { 
     var c = document.getElementsByName("chk"); 
     var k=false; 
      for(var i=0; i<c.length; i++) 
      { 
      if(c[i].checked) 
      { 
       k=true; 
       return(true); 
      } 
      } 
     if(k){ 
       return(true); 
       } 
       else{ 
       alert("Select one environment"); 
       return(false); 
       } 
      var ap = form.getElementById("a1"); 
      if(ap.value == "" || ap.length == 0) 
     { 
     alert("Enter the path"); 
     ap.setfocus(); 
     return(false); 
     } 
      else 
      { 
      return(true); 
      } 

        var p = form.getElementById("a2"); 
      if(p.value == "" || p.length == 0) 

     { 
     alert("Enter the path"); 
     form.p.setfocus(); 
     return(false); 
     } 


     return(true); 
      } 


      </script> 
     </head> 

    <body> 
    <form action="/car.java" onsubmit="return validator(this);"> 
     <br /> 
     <p> 
      <input name="chk" type="checkbox" />One 
      <input name="chk" type="checkbox" />Two 
      <input name="chk" type="checkbox" />Three 
     </p> 
     <br /> 
     <input name="a1" id="a1" size="123" style="width: 766px; height: 21px;" type="text" /> 
     </p> 
     <p> 
      <input name="a2" id="a2" size="123" style="width: 766px; height: 21px;" 
       type="text" /> 
     </p> 
     <textarea cols="95" name="status" rows="11"></textarea> 
     <input name="sub" size="28" style="width: 156px; height: 29px;" type="button" 
     value="Submit" /> 
     </p> 
     </form> 
     </body> 
     </html> 

回答

1

问题在于你的函数,你在程序结束之前用文本字段验证返回一个值。您需要捕获变量的返回值,并在方法结束时返回其值。

像这样

function validator() { 
var c = document.getElementsByName("chk"); 
var k = false, 
    isValid = false; 
for (var i = 0; i < c.length; i++) { 
    if (c[i].checked) { 
     k = true; 
    } 
} 
if (k) { 
    isValid = true; 
} else { 
    alert("Select one environment"); 
} 
var ap = form.getElementById("a1"); 
if (ap.value == "" || ap.length == 0) { 
    alert("Enter the path"); 
    ap.setfocus(); 
} else { 
    isValid = true; 
} 
var p = form.getElementById("a2"); 
if (p.value == "" || p.length == 0) 
{ 
    alert("Enter the path"); 
    form.p.setfocus(); 
} 
return isValid; 
} 
+0

你可以让我知道其中的部分代码,我应该做出改变 – user1815823 2013-04-07 03:10:01

+0

让我编辑自己的帖子 – bipsa 2013-04-07 14:17:57

+0

不过它抛出“选择一个环境”,并进入下一个页。它不会提示文本框 – user1815823 2013-04-07 16:19:37

0
if(ap.value == "" || ap.length == 0) 

我认为你的意思ap.value.length == 0,但无论哪种方式,因为你已经检查了空字符串它是多余的。只需要if(!ap.value)就可以。另外,在文本框部分甚至运行之前,您就是return

也就是说,你应该考虑使用HTML5 Form Validation。它更干净,可以防止出现这样的问题。