If statement works but when I add else nothing works

Viewed 42

I'm making password hide/show toggle with jQuery, when I add two buttons one for show and the other one for hide everything works perfectly but i want to toggle here's the code

jQuery

$(document).ready(function(){
    $('.1').on('click',function(){
        var pass = $('.password');
        if(pass.attr('type','password')){
            pass.attr('type','text');
        }
        else{
            pass.attr('type','password');
        }
    })
})

HTML

<div id="main">
    <h1>Form</h1>
    Enter your login <input class="login">
    Enter password here <input class="password" type="password">
    <button class="1">Show password</button>
</div>
2 Answers

Correct you if() condition like below:

if(pass.attr('type') ==='password')){

I will try to do it like below:

function togglePassword(obj) {
  var x = document.getElementById("password");
  if (x.type === "password") {
    x.type = "text";
    $(obj).html('Hide Password');
  } else {
    x.type = "password";
    $(obj).html('Show Password');
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="main">
  <h1>Form</h1>
  Enter your login <input class="login"><br>
  <!-- converted  class to id to make it unique -->
  Enter password here <input id="password" type="password"><br>
  <button onclick="togglePassword(this)">Show Password</button>
</div>

Please try with the following:

$(document).ready(function(){
    $('.1').on('click',function(){
        var current_type = $('.password').attr('type');
        if(current_type == 'password'){
            $('.password').attr('type','text');
        }
        else{
            $('.password').attr('type','password');
        }
    });
})
Related