Eder Iraizoz
Eder Iraizoz

Reputation: 113

Revealing input type="password"

I'm trying to make a button to reveal the password written on the input. My poor JS skills tell me that I can achieve it by doing something like this:

I tried this:

$('#passReveal').on('click', function(){
    $( "#input-show" ).attr('type', 'text');
    if ($( "#input-show" ).attr('type', 'text')){
        $( "#input-show" ).attr('type', 'password');
    }
});

But doesn't work.

I think this one is the closest, but I have a bug: you must click twice the button to make it work the first time, why is that?

$('#passReveal').on('click', function(){
    $( "#input-show" ).attr('type', 'text');
    $( "#input-show" ).toggleClass('passRevealed');
    if ($( "#input-show" ).hasClass('passRevealed')){  
        $( "#input-show" ).attr('type', 'password');        
    }
});

https://jsfiddle.net/tepLkc7u/2/

I hope you understand my bad english, im learning :)

Upvotes: 0

Views: 1223

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074475

You can't reliably change the type of an input, cross-browser.

What you can do instead is put two inputs next to each other and choose which one to show:

$('#passReveal').on('click', function() {
  var show = $("#input-show"),
      pass = $("#input-pass"),
      showing = show.is(":visible"),
      from = showing ? show : pass,
      to = showing ? pass : show;
  from.hide();
  to.val(from.val()).show();
  $(this).text(showing ? "Reveal" : "Hide");
});
<input type="password" id="input-pass" placeholder="Password">
<input type="text" id="input-show" placeholder="Password" style="display: none">
<button id="passReveal">Reveal</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Upvotes: 6

AmmarCSE
AmmarCSE

Reputation: 30557

What you were doing is toggling the class and then setting the input type to password if it had the class.

So, since it had the class the first time(it was toggled in), it would make the input type back to a password.

The second time, it would not because the input no longer had the class.

Nevertheless, to make it work the first time try

$('#passReveal').on('click', function() {
  $("#input-show").attr('type', 'text');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<input type="password" id="input-show" placeholder="Password">
<button id="passReveal">Reveal</button>

Update

If you wish to achieve IE-Compatibility beware of changing the type attribute dynamically. Rather, follow the approach of using two seperate inputs like in @T.J. Crowders answer.

See Changing <input> type using jQuery with cross browser support and notes about cross-browser consistency in attr()

Upvotes: 0

Related Questions