Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

221
Visualizações
Button type submit - How to validate first

I have a form with a submit button. I can not change it and anything about the 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>

This is my 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);

But if I click on my submit button, the page "recharge" and I can not do the login properly.

I should click the submit button and wait for the username and password to be correct.

How can I click the submit button and not instantly recharge the page?

Thank you so much

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Try this. It prevents the default action for the submit button and lets you perform your own code:

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

More about that: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit_event

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda