为什么单击提交按钮会提交此表单

时间:2011-09-16 10:19:17

标签: javascript

<script type="text/javascript">
var geid = function(x) {
        var element = document.getElementById(x);
        return element;
     }          


function submitForm(){
var password = geid('password').value; 
var passwordConfirm = geid('passwordConfirm');

//THIS IS OF HIGH IMPORTANCE THAT THIS CONFIRM PASSWORD MATCHES
//WILL NEED TO VALIDATE IT IN THE PHP AS WELL>
else if (password == ""){
    registerMessage.innerHTML = "Please enter your Password.";
    return false;  
}
else if (passwordConfirm == "") {
    registerMessage.innerHTML = "Please confirm your password.";            
    return false; 
}

else if (passwordConfirm != password) {
    registerMessage.innerHTML = "Your passwords don't match.";          
    return false; 
}
else {
     registerMessage.innerHTML = "Taking you to your profile, please wait a moment...";
     document.forms['registerform'].submit();
}
}

   <form method="post" action="register.php" id="registerform" onsubmit="return submitForm()">


     <label for="password" class="registerLabel">Password</label>
     <input type="password" name="password" id="password" class="registerText" /> <br />

     <label for="passwordConfirm" class="registerLabel">Confirm Password</label>
     <input type="password" name="passwordConfirm" id="passwordConfirm" class="registerText" /> <br />


        <div class="submitMessage">
            <input type="submit" id="submit" name="submit" value="Register" class="registerButton cleangray" /><br />
            <div id="registerMessage"><?php echo $error ?></div>  
        </div>

        <div class="clear"></div>

    </form>

2 个答案:

答案 0 :(得分:4)

你不能从else if开始;你需要从if

开始
if (password == ""){
    registerMessage.innerHTML = "Please enter your Password.";
    return false;  
}

这阻止了您的任何验证代码运行,只是使用标准提交机制提交表单。

这也不是接近验证的最佳方式。您可以构建一系列消息并一次性全部报告,而不是在每个错误时返回。这样,用户就会知道错误的一切 - 您当前的方法只会设置一条消息。

答案 1 :(得分:2)

由于JavaScript中存在错误,因此您首先使用else if而未定义if。由于此错误,所有JavaScript代码都会失败。

更改

else if (password == ""){

if (password == ""){

工作演示http://jsfiddle.net/Zs3km/

您的代码中的BTW HTML在<script>标记内,不确定它是否是您的错误。您必须在<script>标记打开之前关闭<form>代码。