Reputation: 15
I have this code to verify data (password) on both the fields whether it is equal.
When I enter the password in the first field and go to second field to re-enter the password I get the error cross (fa-close) at that time.
Instead I need that after I get out of second field, after that I get the error message.
HTML:
<input type="password" name="password" id="password" /><br>
<input type="password" name="password2" id="password2" onKeyUp="checkPass(); return false;" />
<span id="confirmMessage" class="confirmMessage"></span>
Here is my javascript code:
<script type="text/javascript">
function checkPass() {
var pass1 = document.getElementById('password');
var pass2 = document.getElementById('password2');
var message = document.getElementById('confirmMessage');
var goodColor = "#fff";
var goodColored = "#087a08";
var badColor = "#fff";
var badColored = "#ed0b0b";
if(password.value == password2.value) {
password2.style.backgroundColor = goodColor;
message.style.color = goodColored;
message.innerHTML = "<i class='fa fa-check'></i>"
}
else {
password2.style.backgroundColor = badColor;
message.style.color = badColored;
message.innerHTML = "<i class='fa fa-close'></i>"
}
}
</script>
Help will be appreciated. Thank you.
Upvotes: 0
Views: 3348
Reputation: 2507
function checkPass() {
var get_elem = document.getElementById,
pass1 = document.getElementById('password'),
pass2 = document.getElementById('password2'),
message = document.getElementById('confirmMessage'),
colors = {
goodColor: "#fff",
goodColored: "#087a08",
badColor: "#fff",
badColored:"#ed0b0b"
},
strings = {
"confirmMessage": ["good", "bad"]
};
if(password.value === password2.value && (password.value + password2.value) !== "") {
password2.style.backgroundColor = colors["goodColor"];
message.style.color = colors["goodColored"];
message.innerHTML = strings["confirmMessage"][0];
}
else if(!(password2.value === "")) {
password2.style.backgroundColor = colors["badColor"];
message.style.color = colors["badColored"];
message.innerHTML = strings["confirmMessage"][1];
}
else {
message.innerHTML = "";
}
}
<input type="password" name="password" id="password" onkeyup="checkPass()" /><br>
<input type="password" name="password2" id="password2" onkeyup="checkPass()" />
<span id="confirmMessage" class="confirmMessage"></span>
How does this code work for you ? We call checkValue()
whenever the user releases a key to deal with cases where the user types something down in the second field and then in the first field (otherwise you would have a "bad" in that case even if the user typed the same thing in both fields). Other than that modification, I didn't do much.
Edit: I wouldn't use the same name for both the id and class attributes of an element (confirmMessage
), see this.
Upvotes: 1
Reputation: 2217
put the checkPass() call on the second password's onblur instead of the the first one or don't check if the second one is empty.
Upvotes: 0