Franco Hauva
Franco Hauva

Reputation: 73

How do i add a password visibility button for a text input

This is part of my code.

<div class="col-md-6">
        
    @Html.Label("Respuestas * (Máximo 50 caracteres)", new { @class = "control-label" })
    @Html.PasswordFor(m => m.PasswordAnswer, new { @class = "form-control", maxlength = 50, type = "text" }) 
    <i class="fa fa-eye-slash" id="togglePassword"></i>
</div>

This is how it ends up looking: This is how it ends up looking

Upvotes: 3

Views: 9766

Answers (4)

Greald Henstra
Greald Henstra

Reputation: 576

<input id="pw" type="password">
    <a
       onmouseover="document.getElementById('pw').type='text'"
       onmouseout ="document.getElementById('pw').type='password'"
    >👁</a>

What this does:

  • hovering the mouse over the 👁 symbol, changes the input fields's type. The starred 'password' will become legible 'text'.
  • moving the mouse away from the 👁 symbol, the input fields's type changes back to starred 'password'.

Upvotes: 0

NVRM
NVRM

Reputation: 13082

Inline, wrapped within a label.

<label>
  <input type=password value=mypass />
  <span onclick="let a=this.parentElement.children[0];(a.type==='password')?a.setAttribute('type','text'):a.setAttribute('type','password')" style=cursor:help>👁</span>
</label>

Upvotes: 0

Sercan
Sercan

Reputation: 5081

In the solution below, the user input is hidden by default, as the type attribute of the <input> element is password. Clicking on the <i> will both change the class applied to the <i> and make the password visible.

const icon = document.getElementById('togglePassword');
let password = document.getElementById('password');

/* Event fired when <i> is clicked */
icon.addEventListener('click', function() {
  if(password.type === "password") {
    password.type = "text";
    icon.classList.add("fa-eye-slash");
    icon.classList.remove("fa-eye");
  }
  else {
    password.type = "password";
    icon.classList.add("fa-eye");
    icon.classList.remove("fa-eye-slash");
  }
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"/>

<div class="col-md-6">
  <label>Password: </label>
  <input type="password" id="password">
    <i class="fa fa-eye" id="togglePassword"></i>
</div>

Upvotes: 5

Kureteiyu
Kureteiyu

Reputation: 629

Your password input will need to have the type password to hide it.

Your button would toggle between the type password and the type text, using javascript.

function togglePasswordVisibility() {
    let e = document.getElementById("togglePassword")
    if (e.type == "password") {
        e.type = "text"
    } else {
        e.type = "password"
    }
}

Upvotes: 3

Related Questions