简体   繁体   English

如何避免在显示警报后提交表单?

[英]How to avoid the form being submitted after displaying alert?

If the user name and password do not match it displays an alert but if I click ok to the alert the form is logged in. Can anyone tell me how to avoid it?如果用户名和密码不匹配,它会显示一个警报,但如果我单击“确定”以发出警报,表单就会登录。谁能告诉我如何避免它? Thanks.谢谢。

<html>
<f:view>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h:form id="loginForm">
<h1><center>Login page</center> </h1>
<h:panelGrid columns="2">
<h:outputLabel value="UserName"></h:outputLabel>
<h:inputText id="name" value="#{user.name}"> </h:inputText>
<h:outputLabel value="Password"></h:outputLabel>
<h:inputSecret id="password" value="#{user.password}"></h:inputSecret>
</h:panelGrid>
<h:commandButton type="button" value="Login" action="logged" onclick="checkPassword(this.form)"></h:commandButton>
</h:form>
</body>
<script type="text/javascript">
<!--
function checkPassword(form) {
var passsword = form["loginForm:password"].value;
var username=form["loginForm:name"].value;
var confirmpassword ="welcome";
var confirmusername="admin";
if((passsword == confirmpassword)&&(username==confirmusername))
form.submit();
else
alert("Username and Password does not match");
}
-->
</script>
</f:view>
</html>
... onclick="checkPassword(this.form); return false;" ...

Change the end of your function to将函数的结尾更改为

else {
    alert("Username and Password does not match");
    return false;
}
if((passsword == confirmpassword)&&(username==confirmusername))
form.submit();

Best not do it like that.最好不要那样做。 If the form is submitted without a button click (eg. in various circumstances when Enter is pressed), your validation won't execute.如果在没有单击按钮的情况下提交表单(例如,在各种情况下按下 Enter 键),您的验证将不会执行。

The best place to put validation is in a form.onsubmit event handler.放置验证的最佳位置是 form.onsubmit 事件处理程序。 eg.: lose the onclick in the source and put the test on the form programmatically:例如:丢失源中的 onclick 并以编程方式将测试放在表单上:

var form= document.getElementById('loginForm');
form.onsubmit= function() {
    var isok= this.elements['loginForm:username'].value=='admin' && this.elements['loginForm:password'].value=='welcome';
    if (!isok)
        alert('Wrong, fool!');
    return isok;
}

You are of course aware that client-side password checking is fruitless.您当然知道客户端密码检查是徒劳的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM