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>
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 in 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 instant recharge the page?
Thank you so much