Search code examples
jquerytypespasswordstogglehide

Jquery input type toggle function


I have made a google login page in which if a user click on eye icons the input type changes from password to text and icon too and vice-versa.The code is below here-

$(document).ready(function(){
  $("#field").on('focus',function(){
$(".mail_placeholder",".pass_placeholder").css("display","none");
    });
    $("#icon").on('click',function(){
var notVisible = $("#pass_field").attr("type","password");
 if (notVisible){
  $("#icon").attr("class","fas fa-eye-slash");
  $("#pass_field").attr("type","text");
  }
  else if(notVisible = false){
    $("#icon").attr("class","fas fa-eye");
  $("#pass_field").attr("type","password");  
  }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="email" class="mail_field" id="text_field" required>
            <div class="mail_placeholder">Enter your email here</div>
            <input type="password" class="pass_field" id="pass_field" required><i class="fas fa-eye" id="icon" style="position:relative; right:6.5%; color:grey;"></i>
            <div class="pass_placeholder">Enter your password here</div>


Solution

  • You just have to check for the attribute type, the following will not work since you are changing the input type not getting the attribute type value:

    var notVisible = $("#pass_field").attr("type","password")
    

    it should be like in the following snippet:

    $(document).ready(function () {
      $("#field").on("focus", function () {
        $(".mail_placeholder", ".pass_placeholder").css("display", "none");
      });
      $("#icon").on("click", function () {
        var notVisible = $("#pass_field").attr("type");
        if (notVisible === "password") {
          $("#icon").attr("class", "fa fa-eye-slash");
          $("#pass_field").attr("type", "text");
        } else {
          $("#icon").attr("class", "fa fa-eye");
          $("#pass_field").attr("type", "password");
        }
      });
    });
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <input type="email" class="mail_field" id="text_field" required />
    <div class="mail_placeholder">Enter your email here</div>
    <input type="password" class="pass_field" id="pass_field" required /><i class="fa fa-eye" id="icon" style="position: relative; right: 6.5%; color: grey;"></i>
    <div class="pass_placeholder">Enter your password here</div>