【问题标题】:Button type submit - How to validate first按钮类型提交 - 如何首先验证
【发布时间】:2022-02-12 20:38:15
【问题描述】:

我有一个带有提交按钮的表单。我无法更改它以及有关 html 的任何内容。

<form>
  <input type="text" class="form-control" id="username" required />
  <label for="username">Username</label>
  <input type="password" class="form-control" id="password" required />
  <label for="password">Password</label>
  <button id="submit" class="btn btn-lg" type="submit">Sign in</button>
  <form></form>
</form>

这是我的 js:

let nombre = document.getElementById("username").value;
let pass = document.getElementById("password").value;

async function login() {
  try {
    const response = await fetch("http://localhost:8888/login", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ username: nombre, password: pass }),
    });
    if (response.status !== 200) throw response.statusText;
    const content = await response.json();
    return content;
  } catch (error) {
    console.log("Errorr:" + error);
  }
}

function submit() {
  let validacion1 = document.getElementById("username").checkValidity();
  let validacion2 = document.getElementById("pass").checkValidity();
  if (validacion1 == true && validacion2 == true) {
    login();
  }
}

document.getElementById("submit").addEventListener("click", submit);

但是如果我点击我的提交按钮,页面会“充值”,我无法正常登录。

我应该点击提交按钮并等待用户名和密码正确。

如何点击提交按钮而不是立即为页面充值?

非常感谢

【问题讨论】:

    标签: javascript html authentication


    【解决方案1】:

    试试这个。它可以防止提交按钮的默认操作,并让您执行自己的代码:

    function submit(event) {
      event.preventDefault();
      let validacion1 = document.getElementById("username").checkValidity();
      let validacion2 = document.getElementById("pass").checkValidity();
      if (validacion1 == true && validacion2 == true) {
        login();
      }
    }
    
    

    更多信息:https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

    【讨论】:

      猜你喜欢
      • 2011-03-31
      • 2016-12-22
      • 2011-01-15
      • 2017-12-29
      • 2015-11-17
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多