首页 > 解决方案 > 我如何制作一个 js 代码来重定向到具有特定输入的特定 html 页面?

问题描述

让我更好地解释一下,我想知道如何创建一个 js 代码来检查 html 输入是否正确,以防它会将您重定向到另一个页面,这是我根据我设法做到的尝试查出。

html部分:

<form name="access" onsubmit="return validate()">
  <input
    type="text"
    id="inputbox"
    value="Password"
    pattern="idkwhatishoouldwriteinhere"
  />
  <input type="submit" value="Submit" />
</form>

js部分:

function validate() {
  if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
    alert("Wrong password");
    document.access.Password.focus();
    return false;
  } else {
    window.open("index.html");
  }
}

如果你想知道为什么我把“答案”放在模式中是因为这应该是一个小彩蛋,我觉得直接看 js 是没有意义的,因为它包含你应该重定向到的链接。在此处输入代码

标签: javascripthtml

解决方案


您需要为您的输入提供 name Password,否则document.access.Password未定义。

function validate() {
  if (document.access.Password.value != "idkwhatishoouldwriteinhere") {
    alert("Wrong password");
    document.access.Password.focus();
    return false;
  } else {
    window.open("index.html")
  }
}
<form name="access" onsubmit="return validate()">
  <input type="text" id="inputbox" value="Password" name="Password" />
  <input type="submit" value="Submit" />
</form>

<!-- password is "idkwhatishoouldwriteinhere" -->


推荐阅读