View Ocutar Password using Editorfor

Asked

Viewed 477 times

1

I’m using Labelfor, I wanted when clicking above to enter the password, displayed the characters, and when clicking outside was hidden, how could I do?

<div class="form-group">
    @Html.LabelFor(model => model.Senha, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Senha, new { htmlAttributes = new { @class = "form-control"} })
        @Html.ValidationMessageFor(model => model.Senha, "", new { @class = "text-danger" })
    </div>
</div>
  • Change the input type to "text" when in focus (onfocus), when not, change to password.

2 answers

1


The logic would be this: when the element <input /> receive the focus, the attribute needs to be changed type for text and when the focus is lost the type for password

Follows examples:


jQuery

$(document).ready(function(e) {
  $('#Senha').on('focus', function() {
    $(this).attr('type', 'text');
  }).on('blur', function() {
    $(this).attr('type', 'password');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="password" id="Senha" name="Senha" value="123" />

Javascript:

(function() {
   var senha = document.getElementById('Senha');
   senha.addEventListener('blur', function()
   {
     senha.setAttribute("type", "password");
   });
   senha.addEventListener('focus', function()
   {
     senha.setAttribute("type", "text");
   });
})();
<input type="password" id="Senha" name="Senha" value="123" />


window.onload = function()
{
   var senha = document.getElementById('Senha');        
   senha.addEventListener('blur', function()
   {
     senha.setAttribute("type", "password");
   });
   senha.addEventListener('focus', function()
   {
     senha.setAttribute("type", "text");
   });
}
<input type="password" id="Senha" name="Senha" value="123" />

References:

  • 1

    Thanks, that’s what I was looking for

  • 1

    I also made an issue by putting with javascript.

  • 1

    I saw, but with Jquery already solved my problem. Thanks

0

I found a simpler solution. Just put the HTML type attribute as below:

@Html.EditorFor(model => model.Senha, new {htmlAttributes = new { @class = "form-control", @type = "password"}})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.