I am trying to make a login form to log in, but when I press Enter or click on button
start , the page appears to reload and lose its data, apart from the fact that it prevents me from displaying a message directly on the form.
only stays with aalert()
const xhr = new XMLHttpRequest();
function registrer() {
console.log("prees registrer");
window.location = 'gestionAlumnos.html'
}
var form = document.getElementById("formLogin");
function prueba() {
var correo = form.elements[0].value;
var contraseña = form.elements[1].value;
login(correo, contraseña)
}
function login(correo, contraseña) {
if (correo === "[email protected]" && contraseña === "password") {
alert("inicio sesión");
} else {
console.log("no funciono");
var text = document.createElement("h1");
text.nodeValue = "error de inicio de sisión";
form.appendChild(text);
}
}
<!DOCTYPE html>
<html lang="en">
<link rel="stylesheet" type="text/css" href="css\citas.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link type="text/css" rel="stylesheet" href="css/materialize.css" media="screen,projection" />
<title>Login</title>
</head>
<body>
<br><br>
<!-- Formulario -->
<div class="container">
<form id="formLogin" class="col s12" style="background-color: rgb(231, 231, 231);" onsubmit="prueba()">
<div class=" center">
<h5 class="header col s12 light">Inicia sesion</h5>
</div>
<div class="row">
<div class="input-field col s12">
<input name="email" type="email" id="email" class="validate" />
<label name="email" for="email">Email</label>
</div>
<div class="input-field col s12">
<input name="contraseña" type="password" id="contraseña" class="validate" />
<label name="contraseña" for="contraseña">Contraseña</label>
</div>
</div>
<div class="button">
<a class="waves-effect waves-teal btn-flat">Resgistrase</a>
<button class="btn waves-effect waves-light" type="submit" name="action">Iniciar
<i class="material-icons right">person</i>
</button>
</div>
</form>
</div>
</body>
</html>
You can use
event.preventDefault()
to prevent the form from reloading the page on submission.In this case, you would have to pass it
event
as a parameter, and within the function putevent.preventDefault()
and that's it.For example:
As they told you above, you can use the prevent default method that is responsible for canceling the default behavior of the form, preventing it from being reloaded. Curiously, you can abbreviate 'event' to just 'e' and it will still work:
Once this is done, the behavior of the form will change and the values you have entered will no longer be reset.