我知道这个主题有几个主题,事实上我从一个这样的线程获得了我的代码,但我似乎无法让它运行。我尝试使用javascript比较HTML表单中的两个输入框。
这是我的JS:
<script>
function checkform(form1)
{
if(form1.password.value != form1.passwordConfirm.value)
{
alert("Passwords must be the same");
form1.password.focus();
return true;
} else {return false;}
}
</script>
这是HTML:
<!Doctype html>
<script type="C:/wamp/www/Table/" src="javascript.js"></script>
<form name="form1" action="demo_form.asp">
Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password cannot be empty')">
<input type="submit" value="Submit" onClick="return checkform(form1);">
</form>
</html>
任何帮助都会很棒!
由于
麦克
答案 0 :(得分:1)
您需要为表单指定id
,然后才能获得该表单。
替换:
<form name="form1" action="demo_form.asp">
使用:
<form name="form1" action="demo_form.asp" id="myForm">
而且这个:
function checkform(form1){
有了这个:
function checkform(){
var form1 = document.getElementById('myForm')
您还需要切换返回语句,以便在PW不匹配时返回false
。
生成的JS / HTML:
function checkform(){
var form1 = document.getElementById('myForm');
if(form1.password.value != form1.passwordConfirm.value)
{
alert("Passwords must be the same");
form1.password.focus();
return false;
}
return true;
}
<form name="form1" action="demo_form.asp" id="myForm">
Username: <input type="text" name="usrname" required oninvalid="this.setCustomValidity('Username cannot be empty.')">
Password: <input type="password" name="password" required oninvalid="this.setCustomValidity('Password cannot be empty')">
Confirm Password: <input type="password" name="passwordConfirm" required oninvalid="this.setCustomValidity('Password cannot be empty')">
<input type="submit" value="Submit" onClick="return checkform();">
</form>
注意我是如何删除第二个return语句周围的else
的。它不需要。
答案 1 :(得分:-1)
从onclick中取出return
。
onClick="checkform(form1);"