Check if passwords are equal jQuery
javascript, jquery
Solution
You should be using `.val()` to get the value of the textbox
You could simplify the whole thing to this:
$('input').blur(function() {
var pass = $('input[name=password]').val();
var repass = $('input[name=repassword]').val();
if(($('input[name=password]').val().length == 0) || ($('input[name=repassword]').val().length == 0)){
$('#password').addClass('has-error');
}
else if (pass != repass) {
$('#password').addClass('has-error');
$('#repassword').addClass('has-error');
}
else {
$('#password').removeClass().addClass('has-success');
$('#repassword').removeClass().addClass('has-success');
}
});
DEMO
You could use `$('input').blur(function()` instead, that way it will trigger on all inputs
Problem
I am trying to validate whether two entered passwords are the same or not. But I can't seem to get it working. No matter what values I enter in my input fields, the result is always "true". Can you see what I am doing wrong? HTML: ``` <div class="form-group" id="password"> <input type="password" class="form-control" placeholder="Password" name="password"> </div> <div class="form-group" id="repassword"> <input type="password" class="form-control" placeholder="Confirm Password" name="repassword"> </div> ``` jQuery: ``` //Check if password is set $('input[name=password]').blur(function() { if($(this).val().length == 0){ $('#password').addClass('has-error'); } else { $('#password').addClass('has-success'); } }); //Check if repassword is set $('input[name=repassword]').blur(function() { if($(this).val().length == 0){ $('#repassword').addClass('has-error'); } else { $('#repassword').addClass('has-success'); } }); //Check if password and repassword are equal $('input[name=password]').blur(function() { if ($(this).attr('value') !== $('input[name=repassword]').attr('value')) { $('#password').addClass('has-error'); $('#repassword').addClass('has-error'); } else { $('#password').addClass('has-success'); $('#repassword').addClass('has-success'); } }); ```