javascript - 使用 Js 在 html 表单中输入正确的密码时导航到 url

标签 javascript html forms

我正在尝试找到一种方法,当用户在我的表单中输入正确的密码时导航到网址,并在输入错误时显示错误警报。我是 js 的新手,并使用这两个链接:Password correct? then redirectAdding 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/

相关文章:

javascript - 如何让 Facebook Like Box "Dark Scheme"正常工作? (背景是透明的。)

javascript - 在 Laravel 项目中调用未定义的函数 asset()

javascript - 带有引用表单值的 javascript 的图像映射区域

php - 尝试使用 WAMPSERVER 保存到数据库时出现 MySQL 连接问题

Javascript ES6 类变量

javascript - wordpress 添加帖子验证

右键单击新选项卡时,Javascript 不执行

javascript - 限制来自输入和文本区域的坏词

html - 背景图片和边框渐变可以共存吗?

javascript - 如何将表单提交到页面,以便该新页面在新窗口(而不是新选项卡)中打开?