I am facing a simple error in js but I can't find it no matter how hard I look
I need to check if the two inputs match, and if so, display a message below.
But from what I see in the console, the input information is not saved in the variables
function passwordCheck(){
var pass = document.getElementById("inputPassword3");
var passCheck = document.getElementById("inputPassword4");
if (pass === passCheck) {
document.getElementById("demo").innerHTML = "Coinciden!";
}
else{
document.getElementById("demo").innerHTML = "no coinciden!";
}
}
<input type="password" id="inputPassword3" required>
<input type="password" id="inputPassword4" required onkeypress="passwordCheck()">
<p id="demo"></p>
The problem, as a colleague commented, is that you did not put
.value
, so instead of comparing their values, you compared the elements, and they were not the same.Also, I improved the code a bit with the following points:
onkeypress
it is preferable to 'set' theevent
from the same script.let
instead ofvar
taking full advantage of the new features of the JS standard.onkeypress
that actually executes theonkeydown
because if not, it will be 'delayed' by one character since it never takes the current one, if not the previous one. The eventinput
indicates the change of the value of theelemento input
.You have to add the value attribute to the end of the input's dom call, because you are comparing the "htmlElement" of the input and not its value so it will always go into the else.
You had two problems that caused your code to not work:
1: What you captured in the variables was the DOM item , not its value. By adding it you extract the value that the .
.value
input
2: The event that you used to call the function did not comply well with the evaluation, since with
onkeypress
it you cannot capture the character that has just been entered, so if, for example, you validate a 4-digit password, the verification of equality would be released by introducing the fifth. To fix it, just use the eventonkeyup
.