不知道是这段代码哪里错了,在验证text是否为空时没有任何反应啊!代码如下:function checkpassword(){ var password=document.getElementById('password').value; var ensurepassword=document.getElementById('ensurepassword').value; if(password==ensurepassword){ return true; }else{ alert("Please check your password!"); document.getElementById('password').focus(); return false; } }function check(form_to_check){ if(checkpassword()){ var elem=form_to_check.elements; var num=elem.length; var i=0; for(i=0;i<num;i++){ if(elem[i].type=="text"&&elem[i].value==""){ alert("Please input something in text!"); elem[i].focus(); return false; }else{ return true; } } } }</script><body><form id="register_form" name="register_form" action="dealregister.php" method="post">...... ..... ......<input type="submit" onsubmit="check(this.form)" value="submit"></form>后来我试了一下手动提交表单,但是连提交都没有反应了。代码如下:function checkpassword(){ var password=document.getElementById('password').value; var ensurepassword=document.getElementById('ensurepassword').value; if(password==ensurepassword){ return true; }else{ alert("Please check your password!"); document.getElementById('password').focus(); return false; } }function check(form_to_check){ if(checkpassword()){ var elem=form_to_check.elements; var num=elem.length; var i=0; for(i=0;i<num;i++){ if(elem[i].type=="text"&&elem[i].value==""){ alert("Please input something in text!"); elem[i].focus(); return false; }else{ document.getElementById('register_form').submit();; } } } }</script><body><form id="register_form" name="register_form" action="dealregister.php" method="post">...... ....... .......<input type="button" id="submit" name="submit" value="submit" onclick="check(this.form)"></form></body>
在html控件内嵌js代码,需要阻止控件默认动作效果的: javascript:return false;你的检查函数在检查失败的时候返回false, onclick="check(this.form)" 仅相当于 onclick="false" ,没有起到阻止表单默认的提交动作,改为onclick="javascript:return check(this.form)" 另外注意,更好的做法是把检查函数应该绑定到form表单的onsubmit 事件上而不是提交按钮js里面绑定表单onsubmit句柄的回调函数: document.getElementById("register_form").onsubmit=check(this)
<input type="button" id="submit" name="submit" value="submit" onclick="check(this.form)">改为<input type="submit" id="submit" name="submit" value="submit" onclick="check(this.form)">