我在 HTML 中有两个文本字段,当单击按钮时,我需要检查它们是否不为空。
但是我有一个工作正常,我的第二个不工作,
这里是代码:
<!DOCTYPE html ">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>appLounge webService</title>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/text.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/960.css" />
<link rel="stylesheet" type="text/css" media="all" href="css/demo2.css" />
<script type='text/javascript'>
function notEmpty(login, password, helperMsg){
if(login.value.length == 0){
alert(helperMsg);
login.focus();
return false;
}
if(password.value.length == 0){
alert(helperMsg);
password.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<div class="container_12">
<!-- login data -->
<div id="header" class="grid_12" style="background : url(img/login.png) no-repeat; background-size: 100%; height: 900px;" >
<form>
<div id="fieldLogin1">
<input type="text" id='req1' name="userName" style="width:530px; height:44px" placeholder="UserName"; /><br />
</div>
<div class="clear"> </div>
<div id="fieldLogin2">
<input type="text" id='req2' name="password" style="width:530px; height:44px" placeholder="Password" />
</div>
<div class="clear"> </div>
<div id="checkBoxRememberMe">
<input type="checkbox" name="remember" value="rememberYes" /> <br />
<form>
<input type='button'
onclick="notEmpty(document.getElementById('req1'), 'req2','Please Enter a Value')"
value='Check Field' />
</form>
</div>
</div> <!-- end .grid_12 -->
<div class="clear"> </div>
</form>
</div>
<!-- end .container_12 -->
</body>
</html>
我已经尝试过
onclick="notEmpty(document.getElementById('req1'), ('req2'),'Please Enter a Value')"
也一样,但也不工作,这是问题所在吗?
非常感谢!
最佳答案
onclick="notEmpty(document.getElementById('req1'), 'req2','Please Enter a Value')"
value='Check Field' />
实际上应该是
onclick="notEmpty(document.getElementById('req1'), document.getElementById('req2'),'Please Enter a Value')"
value='Check Field' />
编辑(由@dante建议):
下面的代码可以更具可读性:
onclick="notEmpty('req1', 'req2', 'Please Enter a Value')"
value='Check Field' />
和
function notEmpty(loginId, passwordId, helperMsg) {
var login = document.getElementById(loginId);
if (!login.value.length) {
alert(helperMsg);
login.focus();
return false;
}
var password = document.getElementById(passwordId);
if (!password.value.length) {
alert(helperMsg);
password.focus();
return false;
}
return true;
}
(顺便说一句,尽可能习惯使用 ===
而不是 ==
,这样你就不会成功(咳咳......)一天将 bool 值与 0
进行比较。它也快一点:))
关于javascript - JS检查两个文本字段是否不为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10481596/