jQuery: Show Password without any plugin

When you search "jquery show password" in Google, the first few search results in the list, will be having a jQuery Plugin to toogle password's visibility using checkbox. Plugins are useful but I don't think that a jQuery plugin is required for this. This is easy to achieve with simple jQuery code. In this post, you will find how to achieve it. So let's start.

HTML Code

First, the HTML part. Define 2 input type textboxes. One with "Password" mode and another with "text" mode. The "text" mode control will be used to show the password and it will be hidden by default.

Password:<input type="password" id="txtPassword" />
<input type="text" id="txthdnPassword" />
<input type="checkbox" id="chkShow"/>Show Password 

jQuery Code

First thing we need to do is to hide the plain textbox. And also make it readonly as well.

$('#txthdnPassword').hide();
$('#txthdnPassword').attr('readonly','readonly');

Now, copy the password textbox value to plain textbox value, whenever focus goes out of password textbox. So use blur() event.

$('#txtPassword').blur(function() {
   $('#txthdnPassword').val($(this).val());
});

Now, the last step is to show/hide textboxes based on checkbox value. So first find out whether it is checked or not. Based on it's status show/hide respective textboxes.

$('#chkShow').change(function() {
  var isChecked = $(this).prop('checked');
  if (isChecked) {
     $('#txtPassword').hide();
     $('#txthdnPassword').show();
  }
  else {
     $('#txtPassword').show();
     $('#txthdnPassword').hide();
  }
});

So complete code is,

$(document).ready(function() {
    $('#txthdnPassword').hide();
    $('#txthdnPassword').attr('readonly','readonly');
    $('#txtPassword').blur(function() {
        $('#txthdnPassword').val($(this).val());
    });

    $('#chkShow').change(function() {
        var isChecked = $(this).prop('checked');
        if (isChecked) {
            $('#txtPassword').hide();
            $('#txthdnPassword').show();
        }
        else {
            $('#txtPassword').show();
            $('#txthdnPassword').hide();
        }
    });
});?

See result below

See Complete Code

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...