我正在获得单个表单的双重警报提示:第一次弹出警报,然后当我单击“确定”时,同一个警告再次弹出。我认为我的代码应该在遇到“else window.alert(sameWarning)时执行一次警报,并在达到”return false()“时停止;但似乎返回false()导致警报两次。也许是因为我有在一个页面上有两个表单;但是,它们有两个单独的函数名称(“signinForm()”和“saveSignUp()”)并调用两个单独的表单(表单[0]和表单[1])?我认为我的代码是正确的,但我现在无法弄明白。任何帮助都会受到赞赏。提前致谢!
<script type="text/javascript">
//FIRST FUNCTION FOR FORMS[0]
function signinForm(){
// var sameWarning = "The required fields were not submitted for the following error(s). \n \n";
var warningLogin = "The following field(s) require an entry: \n \n";
var sameWarning = warningLogin;
var userName = document.forms[0].userName.value;
var pswd = document.forms[0].pswd.value;
if(userName == ""){
sameWarning += " - First Name \n";
}
if(pswd == ""){
sameWarning += " - Password \n";
}
if (warningLogin == sameWarning){
return true;
}
else {
window.alert(sameWarning);
}
return false;
}
//SECOND FUNCTION CALL FOR FORMS[1]
function saveSignUp(){
// var warning = "The required fields were not submitted for the following error(s). \n \n";
var warning = "The following field(s) require an entry: \n \n";
var same = warning;
var firstName = document.forms[1].firstName.value;
var lastName = document.forms[1].lastName.value;
var email = document.forms[1].email.value;
var phone = document.forms[1].phoneNumber.value;
if(firstName == ""){
//firstName.style.backgroundColor="red";
warning += " - First Name \n";
}
if(lastName == ""){
warning += " - Last Name \n";
}
if(email == ""){
warning += " - Email \n";
}
if(phone == ""){
warning += " - Work Phone \n";
}
if(phone < 5 ){
warning += " - Must be a numberssss \n";
}
if (warning == same){
return true;
}
else {
alert(warning);
}
return false;
}
</script>
HTML
<h1>Login</h1>
<form method="post" onsubmit="return signinForm();" action="" >
<input type="text" placeholder="Username/Email" name="userName">
<input type="password" placeholder="Password" name="pswd" id="pswd">
<input type="submit" onclick="signinForm();" value="Sign In">
</form>
<h1>Sign Up!</h1>
<form method="post" onsubmit="return saveSignUp()" action="" >
<input type="text" placeholder="First Name" name="firstName">
<input type="text" placeholder="Last Name" name="lastName">
<input type="text" placeholder="Email" name="email">
<input type="text" placeholder="Phone Number" name="phoneNumber">
<input type="submit" onclick="saveSignUp();" class="button wide" value="Request an Account">
答案 0 :(得分:1)
这是因为你两次致电signinForm();
。
删除其中一个侦听器
onclick="signinForm();"
onsubmit="return signinForm()"
当您点击提交按钮时,请致电signinForm();
。因为它是submit
按钮,它会触发onsubmit
事件,并调用return signinForm()
答案 1 :(得分:1)
当你点击提交时,首先它会触发click事件(调用你的函数),然后它会触发一个提交事件(再次调用你的函数)。只需删除提交按钮的onclick。