popsagirl popsagirl - 1 year ago 58
CSS Question

js/jquery Div not showing when criteria met

I have the following code. I want the Div with id '#register-password-error' to appear when the two password fields do not match and when they match nothing to appear. At the moment nothing happens. Here is the code



function checkPasswordMatch() {
var password = document.getElementById('inital-password').value;
var confirmPassword = document.getElementById('confirm-password').value;

if (password === confirmPassword) {
$("#register-password-error").hide();
} else {
$('#register-password-error').show();
}
}

$(document).ready(function() {
$("#initial-password", "#confirm-password").keyup(checkPasswordMatch);
});

.register-password-error {
display: none;
height: 30px;
width: 100%;
background-color: red;
color: #FFF;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="password" placeholder="Password" id="inital-password" />
<input type="password" placeholder="Confirm Password" id="confirm-password" onChange="checkPasswordMatch();" />
<div class="register-password-error">Passwords do not match!</div>





I am using a CDN for JS and jQuery

Any help much appreciated!

Answer Source

You were mixing up id and class, so I fixed that. It all now uses #initial-password.

Also you had some spelling errors: inital-password vs initial-password. Spelling matters!

Furthermore the jQuery selector for the keyup event was incorrect.

Finally, I removed the now redundant onChange="checkPasswordMatch();" from the HTML part.

Working demo:

function checkPasswordMatch() {
  var password = document.getElementById('initial-password').value;
  var confirmPassword = document.getElementById('confirm-password').value;

  if (password === confirmPassword) {
    $("#register-password-error").hide();
  } else {
    $('#register-password-error').show();
  }
}

$(document).ready(function() {
  $("#initial-password, #confirm-password").keyup(checkPasswordMatch);
});
#register-password-error {
  display: none;
  height: 30px;
  width: 100%;
  background-color: red;
  color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="password" placeholder="Password" id="initial-password" />
<input type="password" placeholder="Confirm Password" id="confirm-password" />
<div id="register-password-error">Passwords do not match!</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download