how to check confirm password field in form without reloading page

We will be looking at two approaches to achieve this. With and without using jQuery.

1. Using jQuery

You need to add a keyup function to both of your password and confirm password fields. The reason being that the text equality should be checked even if the password field changes. Thanks @kdjernigan for pointing that out

In this way, when you type in the field you will know if the password is same or not:

$('#password, #confirm_password').on('keyup', function () {
  if ($('#password').val() == $('#confirm_password').val()) {
    $('#message').html('Matching').css('color', 'green');
  } else 
    $('#message').html('Not Matching').css('color', 'red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>password :
  <input name="password" id="password" type="password" />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password" />
  <span id='message'></span>
</label>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/325/

2. Without using jQuery

We will use the onkeyup event of javascript on both the fields to achieve the same effect.

var check = function() {
  if (document.getElementById('password').value ==
    document.getElementById('confirm_password').value) {
    document.getElementById('message').style.color="green";
    document.getElementById('message').innerHTML = 'matching';
  } else {
    document.getElementById('message').style.color="red";
    document.getElementById('message').innerHTML = 'not matching';
  }
}
<label>password :
  <input name="password" id="password" type="password" onkeyup='check();' />
</label>
<br>
<label>confirm password:
  <input type="password" name="confirm_password" id="confirm_password"  onkeyup='check();' /> 
  <span id='message'></span>
</label>

and here is the fiddle: http://jsfiddle.net/aelor/F6sEv/324/

Leave a Comment