[英]Javascript with html form validation not working
i'm trying to validate a form using a simple javascript script however it is not working, can anyone tell me what is wrong with my code? 我正在尝试使用简单的JavaScript脚本来验证表单,但是它无法正常工作,有人可以告诉我我的代码有什么问题吗? (sorry for my vague question)
(对不起我的模糊问题)
JS code: JS代码:
<script type="text/javascript">
function validation()
{
var fName=document.forms["teacherReg"]["firstname"].value;
var lName=document.forms["teacherReg"]["lastname"].value;
var uName=document.forms["teacherReg"]["username"].value;
var pWord=document.forms["teacherReg"]["password"].value;
var cPWord=document.forms["teacherReg"]["confirmpassword"].value;
if (fName="" || lName="" || uName="" || pWord="")
{
alert("Not a valid entry");
return false;
}
}
</script>
html form: html形式:
<form name="teacherReg" action="" method="POST" onsubmit="return validation();">
1. First name:
2. Last name:<br/><input type="text" name="firstname" id="firstname" />
<input type="text" name="lastname" id="lastname" /><br/><br/>
3. Desired Username:
<br/><input type="text" name="username" id="username" /><br/><br/>
4. Desired Password:
5. Confirm Password:<br/><input type="password" name="password" id="password" />
<input type="password" name="confirmpassword" id="confirmpassword" /> <br/><br/>
<center><input type="submit" value="Register" name="submitbutton" class="button" /></center>
</form>
I expect it to return false if any of the fields "fName, lName, uName, pWord" are blank, however it is always returning true 如果任何字段“ fName,lName,uName,pWord”为空,我希望它返回false,但是始终返回true
The problem is that you confused =
(assignment operator) operator with ==
(comparison operator): 问题是您将
=
(赋值运算符)运算符与==
(比较运算符)混淆了:
if (fName = "" || lName = "" || uName = "" || pWord = "") {
It should be 它应该是
if (fName == "" || lName == "" || uName == "" || pWord == "") {
这就是问题:
if (fName=="" || lName=="" || uName=="" || pWord=="")
=
is assignment operator , where ==
is comparison operator. =
是赋值运算符,其中==
是比较运算符。 use ==
for comparing values. 使用
==
比较值。
使用比较运算符==
代替赋值运算符=
。
Please try to use the ID instead of the form object. 请尝试使用ID而不是表单对象。
function validation(){
var username = document.getElementById('username').value;
// etc.
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.