我只想单击一个按钮,然后,如果您输入的密码正确,它应该将您重定向到另一个页面,但如果您输入错误,它应该什么也不做。
下面的代码有效,但如果您出错,它也会将您重定向到成功页面。我只是希望它仅在您正确时才重定向。
<div class="wrapper">
<form class="form1" action="http://google.com">
<div class="formtitle">
Enter the password to proceed
</div>
<div class="input nobottomborder">
<div class="inputtext">
Password:
</div>
<div class="inputcontent">
<input type="password" id="password" /><br />
</div>
</div>
<div class="buttons">
<input class="orangebutton" type="submit" value="Login" onclick="if (document.getElementById('password').value == 'hello') alert('Correct Password!'); else alert('Wrong Password!');" />
</div>
</form>
</div>
最佳答案
当密码不同时,您必须添加 return false。这可以防止默认操作和事件传播。如果您有此选项,您还可以使用 jquery 来获取元素及其值。
这取决于您希望如何在服务器端处理或仅在客户端处理。 仅在客户端,我们可以将 type="submit"更改为 type="button"。
<div class="wrapper">
<form class="form1" action="http://google.com">
<div class="formtitle">
Enter the password to proceed
</div>
<div class="input nobottomborder">
<div class="inputtext">
Password:
</div>
<div class="inputcontent">
<input type="password" id="password" /><br />
</div>
</div>
<div class="buttons">
<input class="orangebutton" type="button" value="Login" onclick="checkPassword()" />
</div>
</form>
</div>
<script>
function checkPassword(){
if(document.getElementById('password').value == 'hello'){
alert('Correct Password!');
location.href = "http://google.com";
} else {
alert('Wrong Password!');
return false;
}
}
</script>
关于输入密码后 JavaScript 简单重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35710019/