The following article will introduce to you how to display and hide passwords using jQuery and JavaScript. I hope it will be helpful to you.
For account security, we always set the password to be very complex; when entering the password, because the password is not displayed, we don’t know whether the input is correct or not. Wrong, it may cause authentication errors. As a result, websites now allow users to toggle to view hidden text in password fields.
The following code example introduces how to use jQuery and JavaScript to display and hide passwords. [Related video tutorial recommendations: JavaScript Tutorial, jQuery Tutorial]
HTML code: First we need to create a basic form layout
<table> <tr> <td>Username : </td> <td><input type='text' id='username' ></td> </tr> <tr> <td>Password : </td> <td><input type='password' id='password' > <input type='checkbox' id='toggle' value='0' onchange='togglePassword(this);'> <span id='toggleText'>Show</span></td> </tr> <tr> <td> </td> <td><input type='button' id='but_reg' value='Sign Up' ></td> </tr> </table>
Instructions: Attach the onchange="togglePassword()" event to the check box element and call the js code to switch the display (or hide) of the password
1. Use JavaScript to implement
<script type="text/javascript"> function togglePassword(el){ // Checked State var checked = el.checked; if(checked){ // Changing type attribute document.getElementById("password").type = 'text'; // Change the Text document.getElementById("toggleText").textContent= "Hide"; }else{ // Changing type attribute document.getElementById("password").type = 'password'; // Change the Text document.getElementById("toggleText").textContent= "Show"; } } </script>
Description:
Check whether the check box is checked. If it is checked, the type attribute of the input box switches to text. If it is not checked, the type attribute remains password.
Rendering:
2. Use jQuery to implement
Import jQuery library
<script type="text/javascript" src="jquery.min.js" ></script>
Use jQuery's attr() method to change the type attribute of the input element.
<script type="text/javascript"> $(document).ready(function(){ $("#toggle").change(function(){ // Check the checkbox state if($(this).is(':checked')){ // Changing type attribute $("#password").attr("type","text"); // Change the Text $("#toggleText").text("隐藏密码"); }else{ // Changing type attribute $("#password").attr("type","password"); // Change the Text $("#toggleText").text("显示密码"); } }); }); </script>
Output:
The above is the entire content of this article, I hope it will be helpful to everyone's learning. For more exciting content, you can pay attention to the relevant tutorial columns of the PHP Chinese website! ! !
The above is the detailed content of How to show and hide passwords using jQuery and JavaScript. For more information, please follow other related articles on the PHP Chinese website!