Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
¿Cómo puedo redirigir a los usuarios después de que hayan iniciado sesión con la instrucción if/else (JavaScript)?

Estoy aprendiendo JavaScript, así que decidí hacer un pequeño proyecto de inicio de sesión simple de declaración if/else. Todo está bien, pero no está redirigiendo.

Si sabe lo que estoy haciendo mal, por favor ayúdeme en un lenguaje sencillo porque lo estoy aprendiendo.

 'use strict' function validate(){ var username=document.getElementById('login-username').value; var passowrd=document.getElementById('login-password').value; if (username === "daksh" && passowrd === 'daksh'){ alert('You have sucessfully logged in'); window.location.href("http://stackoverflow.com"); } else{ alert('Wrong username or password'); return true; } }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="login.css"> <title>Login</title> <script src="login.js"></script> </head> <body> <DIV class="container"> <form method="POST" class="login-form"> <h1 class="login-heading">LOGIN FORM</h1> <input type="text" placeholder="User Name" id="login-username"> <br><br> <input type="password" placeholder="Password" id="login-password"> <br><br><br> <input type="submit" value="Login" id="login-submit" onclick="validate()"> </form> </DIV> </body> </html>

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

  1. SIEMPRE use el controlador de eventos de envío en un formulario, NUNCA el botón de envío: desea bloquear el envío en caso de error o, en su caso, bloquear porque usted mismo está manejando el procesamiento.
  2. Use eventListener en lugar del controlador de eventos en línea
  3. Usas location.href como una función, no lo es. Puede usar location.replace(href) si lo desea
  4. Por razones obvias de seguridad, no realice la validación de la contraseña del lado del cliente, pero supongo que es solo con fines de aprendizaje.

 window.addEventListener("load", function() { // when the page has loaded document.getElementById("myForm").addEventListener("submit", function(e) { // passing the event e.preventDefault(); // you do not want to let the form submit because you handle the nex page const username = document.getElementById('login-username').value; const password = document.getElementById('login-password').value; if (username === "daksh" && password === 'daksh') { alert('You have sucessfully logged in'); window.location.href = "http://stackoverflow.com"; } else { alert('Wrong username or password'); } }) })
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="login.css"> <title>Login</title> <script src="login.js"></script> </head> <body> <div class="container"> <form method="POST" class="login-form" id="myForm"> <h1 class="login-heading">LOGIN FORM</h1> <input type="text" placeholder="User Name" id="login-username"> <br><br> <input type="password" placeholder="Password" id="login-password"> <br><br><br> <input type="submit" value="Login" id="login-submit"> </form> </div> </body> </html>

about 4 years ago · Juan Pablo Isaza Report

0

window.location.href es una propiedad, no un método, por lo que su código debería ser como:

 window.location.href = "http://stackoverflow.com";

Más información al respecto en MDN Web Docs

about 4 years ago · Juan Pablo Isaza Report

0

window.location.href no es una función. Debe asignar la URL a window.location.href.

 window.location.href = 'http://stackoverflow.com';

Sin embargo, window.location.href simula un clic. Si desea simular una redirección HTTP, use window.location.replace en su lugar.

 window.location.replace('http://stackoverflow.com');

Editar: también está enviando el formulario, porque hay un método de formulario y una entrada de envío especificada. Esto desencadena una publicación de formulario y, debido a que no se especifica ninguna acción, volverá a cargar la página. Elimine el método de formulario y use un botón en su lugar.

 function validate(){ var username=document.getElementById('login-username').value; var passowrd=document.getElementById('login-password').value; if (username === "daksh" && passowrd === 'daksh'){ alert('You have sucessfully logged in'); location.href = 'http://stackoverflow.com'; } else{ alert('Wrong username or password'); return true; } }
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Login</title> </head> <body> <DIV class="container"> <form class="login-form"> <h1 class="login-heading">LOGIN FORM</h1> <input type="text" placeholder="User Name" id="login-username"> <br><br> <input type="password" placeholder="Password" id="login-password"> <br><br><br> <button type="button" value="Login" id="login-submit" onclick="validate()" value="login">Login</button> </form> </DIV> </body> </html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!