Arek Wiśniewski
Arek Wiśniewski

Reputation: 73

Button "show password" not working

I would like to write the button which show password from dots. I mean, just change attribute "type" from password to text and when I will click again that button, password should be hide.

My code:

$(document).ready(function(){
  var fieldType = $('input.password').attr("type");

  $('.show_passwrd').on("click",function(){
      if(fieldType == "password"){
          $('input.password').attr("type","text");
      }
      else{
          $('input.password').attr("type","password");
      }
  })
});

I do not have any errors in my browser just when I will click, nothing do.

Upvotes: 0

Views: 365

Answers (2)

dana
dana

Reputation: 18135

Move the code that checks the current type into the event handler. This value will change every time .show_passwrd is clicked and needs to be recomputed.

jQuery(function($) {
    $('.show_passwrd').on("click", function() {
        var fieldType = $('input.password').attr("type");
        if (fieldType == "password"){
            $('input.password').attr("type","text");
        } else {
            $('input.password').attr("type","password");
        }
    });
});

Another thing to note is that the selector input.password is looking for an <input> tag with CSS class of password. You may have to add it if it isn't already there or change the selector to get the element by ID:

<input type="password" class="password">

Upvotes: 3

Dave
Dave

Reputation: 10924

Like dana suggested, you need to check for the fieldType inside the click handler. Also, it could be a problem with your selectors. I've shown the HTML below that would be needed to make the JavaScript work.

$(document).ready(function() {
  $('.show_passwrd').on("click", function() {
    var fieldType = $('input.password').attr("type");
    if (fieldType == "password") {
      $('input.password').attr("type", "text");
    } else {
      $('input.password').attr("type", "password");
    }
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input class="password" value="password" />
<input type="button" class="show_passwrd" value="show password" />

Upvotes: 1

Related Questions