Tuesday 23 February 2021

Change TextBox TextMode to Password using jQuery

 In this article I will explain with an example, how to change TextBox TextMode to Password using jQuery.

The TextMode of a TextBox is decided by its Type attribute i.e. input or password.
HTML does not allow the Type attribute to be modified with jQuery at runtime and hence the same can be achieved by creating a dynamic TextBox next to the Password TextBox and hiding the Password TextBox.
 
 
HTML Markup
The HTML Markup consists of an HTML Password TextBox and a CheckBox.
<table border="0" cellpadding="0" cellspacing="0">
    <tr>
        <td>Password</td>
        <td><input type="password" id="txtPassword" /></td>
    </tr>
    <tr>
        <td><label for="chkShowPassword">
                <input id="chkShowPassword" type="checkbox" />
                Show password</label>
        </td>
    </tr>
</table>
 
 
Changing TextBox TextMode to Password using jQuery
Inside the jQuery document ready event handler, the CheckBox has been assigned a Click event handler.
If the CheckBox is checked, a dynamic TextBox element is created and appended next to it and the Password TextBox is hidden.
If the CheckBox is unchecked, the dynamic TextBox element is removed and the Password TextBox is shown again.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#chkShowPassword").bind("click"function () {
            var txtPassword = $("#txtPassword");
            if ($(this).is(":checked")) {
                txtPassword.after('<input onchange = "PasswordChanged(this);" id = "txt_' + txtPassword.attr("id") + '" type = "text" value = "' + txtPassword.val() + '" />');
                txtPassword.hide();
            } else {
                txtPassword.val(txtPassword.next().val());
                txtPassword.next().remove();
                txtPassword.show();
            }
        });
    });
    function PasswordChanged(txt) {
        $(txt).prev().val($(txt).val());
    };
</script>
 
 
Screenshot
Change TextBox TextMode to Password using jQuery
 
 
Browser Compatibility

The above code has been tested in the following browsers.

Internet Explorer  FireFox  Chrome  Safari  Opera 

* All browser logos displayed above are property of their respective owners.

No comments:

Post a Comment