I have a form with a submit button. I can not change it and anything about the html.
<form>
<input type="text" id="username" required />
<label for="username">Username</label>
<input type="password" id="password" required />
<label for="password">Password</label>
<button id="submit" 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
CodePudding user response:
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