我正在尝试找到一种方法,当用户在我的表单中输入正确的密码时导航到网址,并在输入错误时显示错误警报。我是 js 的新手,并使用这两个链接:Password correct? then redirect 和 Adding an onclick function to go to url in javascript? 将我当前的代码放在一起。我当前的代码是:
<form class="hero-form">
<fieldset>
<div class="row-fluid">
<label>Enter your passcode</label>
<input type="password" name="password" maxlength="8" class="span7" id="password" placeholder="e.g. 12345678" required/>
<button class="btn btn-info btn-large span5" id="joe_btn" input type="submit" value="Submit" onclick="if (document.getElementById('password').value == '12345678') location.href = 'http://example.url.here'; else alert('Please check your passcode and try again');">Enter</button>
</div>
</fieldset>
</form>
到目前为止,如果密码正确,我可以让它返回警报,但一旦我更换:
alert('congrats, correct password')
这样就不行了:
location.href = 'http://your.url.here'
任何帮助将不胜感激。请发布您的回复的完整代码,因为我是 js 的绝对初学者,如果您只发布代码片段,很容易会错过一些东西。
谢谢各位,
最佳答案
你的代码应该是这样的:
<script type="text/javascript">
function onSubmit() {
if (document.getElementById('password').value == '12345678') {window.location.href = 'http://google.co.in'; }else{ alert('Please check your passcode and try again');}
}
</script>
<fieldset><form class="hero-form" action="#">
<div class="row-fluid">
<label>Enter your passcode</label>
<input type="password" name="password" maxlength="8" class="span7" id="password" placeholder="e.g. 12345678" required/>
</div>
</form></fieldset>
<button class="btn btn-info btn-large span5" id="joe_btn" onclick="onSubmit()">Enter</button>
您的错误:该按钮不应提交表单,因此我已将其放在表单之外。我已将 location.href 更新为 window.location.href
希望它能起作用。
关于javascript - 使用 Js 在 html 表单中输入正确的密码时导航到 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23146691/