[英]validation is not working if text field and button are not in the same form tag
[英]Validation of Text field not working
我有帶有復選框和文本字段的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>
問題出在您的函數上,您要在程序完成文本字段驗證之前返回一個值。 您需要捕獲變量的返回值,並在方法結束時僅返回一次它的值。
像這樣的東西
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;
}
if(ap.value == "" || ap.length == 0)
我認為您的意思是ap.value.length == 0
,但是無論哪種方式都是多余的,因為您已經檢查了空字符串。 只是if(!ap.value)
會做。 此外,您將在文本框部件尚未運行之前return
。
也就是說,您應該考慮使用HTML5表單驗證。 它更清潔,可以防止此類問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.