Compare values of "input" elements with javascript or jQuery

1

Well, I tried to make this fiddle to understand how to do element condition comparisons with javascript, but I do not know what went wrong.

var username = "admin";
var password = "admin";


function validarUsuarioSenha() {

  if ($("#usuario").value() == username && $("#senha").value() == password) {

    $("#loginCorreto").show();
  } else {

    $("#loginErrado").show();
  }

}
#loginCorreto {
  width: 235px;
  height: 20px;
  background: green;
  color: #FFFFFF;
  display: none;
}
#loginErrado {
  width: 235px;
  height: 20px;
  background: red;
  color: #FFFFFF;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="usuario" type="text" placeholder="Digite seu login: " />
<br/>
<br/>
<input id="senha" type="password" placeholder="Digite sua senha: " />
<br/>
<br/>
<input type="button" value="Fazer login" onclick="validarUsuarioSenha()" />
<br/>
<br/>
<div id="loginCorreto">Login efetuado com sucesso!</div>
<div id="loginErrado">Usuário ou senha inválidos!</div>
    
asked by anonymous 03.06.2015 / 01:14

2 answers

2

Use $("elemento").val() not .value() :

var username = "admin";
var password = "admin";


function validarUsuarioSenha() {

  if ($("#usuario").val() == username && $("#senha").val() == password) {

    $("#loginCorreto").show();
    $("#loginErrado").hide();
  } else {
    $("#loginErrado").show();
    $("#loginCorreto").hide();
  }

}
#loginCorreto {
  width: 235px;
  height: 20px;
  background: green;
  color: #FFFFFF;
  display: none;
}
#loginErrado {
  width: 235px;
  height: 20px;
  background: red;
  color: #FFFFFF;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="usuario" type="text" placeholder="Digite seu login: " />
<br/>
<br/>
<input id="senha" type="password" placeholder="Digite sua senha: " />
<br/>
<br/>
<input type="button" value="Fazer login" onclick="validarUsuarioSenha()" />
<br/>
<br/>
<div id="loginCorreto">Login efetuado com sucesso!</div>
<div id="loginErrado">Usuário ou senha inválidos!</div>
    
03.06.2015 / 01:51
1

A DOM element of type input has a value property. So using native JavaScript you can know the value at the moment using el.value .

When you use jQuery you run a function / method called .val() . What jQuery will do is basically run a function to return the value property. Hence the relatives who invoke the function.  You could get the same using .prop(value) .

In this specific case using jQuery is unnecessary. Native JavaScript works equally on all Browsers.

An example would be:

var jVal = $('input').val();
var jProp = $('input').prop('value');
var nativo = document.querySelector('input').value;

console.log(jVal, jProp, nativo); // dá o mesmo em todos

Your code will work:

03.06.2015 / 22:50