0
I have the following code JS
:
var botao = document.querySelector('input[type="submit"]');
botao.addEventListener('click', function(e) {
let form = document.querySelector('form');
let ipt = {
nome: form.nome.value,
senha: form.senha.value
}
var users = [
{nome: "Jorge", senha: "123"},
{nome: "Joao", senha: "joao"},
{nome: "Maria", senha: "maria"},
{nome: "José", senha: "jose"},
{nome: "Ana", senha: "ana"},
]
for(let i = 0; i<users.length; i++) {
if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
e.preventDefault();
alert('Bem vindo ' + form.nome.value + " !");
window.location.href= "http://www.google.com";
}
else {
e.preventDefault();
alert('Dados incorretos!');
}
}
});
and the following html
:
<form name="form1" id="form1">
<input name="nome" type="text" placeholder="Usuário "/>
<input name="senha" type="password" placeholder="Senha "/>
<input type="submit" value="Login"/>
</form>
I’m doing a check according to the vector indices users
, the problem is: When verifying that the user exists, it will print Dados incorretos
until you arrive at the correct index and print the welcome message and make the redirect.
See the example below:
var botao = document.querySelector('input[type="submit"]');
botao.addEventListener('click', function(e) {
let form = document.querySelector('form');
let ipt = {
nome: form.nome.value,
senha: form.senha.value
}
var users = [
{nome: "Jorge", senha: "123"},
{nome: "Joao", senha: "joao"},
{nome: "Maria", senha: "maria"},
{nome: "José", senha: "jose"},
{nome: "Ana", senha: "ana"},
]
for(let i = 0; i<users.length; i++) {
if (ipt.nome == users[i].nome && ipt.senha == users[i].senha) {
e.preventDefault();
console.log('Bem vindo ' + form.nome.value + " !");
//window.location.href= "http://www.google.com";
}
else {
e.preventDefault();
console.log('Dados incorretos!');
}
}
});
<form name="form1" id="form1">
<input name="nome" type="text" value="Ana" placeholder="Usuário "/>
<input name="senha" value="ana" type="password" placeholder="Senha "/>
<input type="submit" value="Login"/>
</form>
See that it prints 4 messages from dados incorretos
and only then print the bem vindo
.
Can someone help me?
Yeah, I was doing it that way, I was wondering if there’s any other way to accomplish the implementation than with a check
booleana
.– Jorge.M
edited the answer with another solution, it may be that instead of
==
be it>
, forehead there– Costamilam
Adding the
else if
have no effect whatsoever.– Jorge.M
you must write the
else
– Costamilam
I was wrong: the right thing is
} else if(i == users.length - 1) {
– Costamilam