In this article I will explain with an example, how to change TextBox TextMode to Password using JavaScript.
The TextMode of a TextBox is decided by its Type attribute i.e. text or password.
HTML does not allow the Type attribute to be modified with JavaScript 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. The CheckBox has been assigned a JavaScript OnClick event handler
<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" onclick="ShowPassword(this)" />
Show password</label>
</td>
</tr>
</table>
JavaScript function for changing TextBox TextMode to Password using JavaScript
Inside the ShowPassword JavaScript function, the reference of the CheckBox is received as parameter.
Then the Password TextBox is referenced and 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">
function ShowPassword(chkShowPassword) {
//Reference the TextBox.
var txtPassword = document.getElementById("txtPassword");
var txtTemp;
//If CheckBox is Checked i.e. Password needs to be shown.
if (chkShowPassword.checked) {
//Remove if any TextBox present next to the Password TextBox.
if (txtPassword.nextSibling != null) {
txtPassword.parentNode.removeChild(txtPassword.nextSibling);
}
//Create a TextBox element and set the value of Password TextBox to it.
txtTemp = document.createElement('INPUT');
txtTemp.setAttribute('TYPE', 'TEXT');
txtTemp.setAttribute('VALUE', txtPassword.value);
//Set the value of TextBox back to Password TextBox on OnChange event.
txtTemp.onchange = function () {
txtPassword.value = this.value;
};
//Insert the TextBox next to the Password TextBox.
txtPassword.parentNode.insertBefore(txtTemp, txtPassword.nextSibling);
//Hide the Password TextBox.
txtPassword.style.display = "none";
} else {
txtTemp = txtPassword.nextSibling;
//Set the value of the TextBox to the Password TextBox.
txtPassword.value = txtTemp.value;
//Remove the TextBox.
txtTemp.parentNode.removeChild(txtTemp);
//Show the Password TextBox.
txtPassword.style.display = "block";
}
};
</script>
Screenshot
Browser Compatibility
The above code has been tested in the following browsers.
* All browser logos displayed above are property of their respective owners.
Demo
Downloads