srithan
srithan

Reputation: 39

why is my JQuery Toggle password visibility is not working?

<p class="input-group pwdField">
   <input type="password" name="password" placeholder="Enter your Password" required>
   <i class="fa fa-eye"></i>
</p>

This is my HTML markup and my jquery code is as below.

$(function() {

    $( ".input-group" ).children("i").click(function() {

        $( this ).toggleClass("fa-eye fa-eye-slash");

        var inputField = $(".pwdField").children().first();

        if ( $(inputField).attr("type", "password") ) {

            $(inputField).attr("type", "text");

        } else {
            $(inputField).attr("type", "password");
        }

    });

}); // End of document.ready();

Please help me, when I am clicking the eye icon in the input field, everythng is working perfectly but when I click again, the input field is not changing its attribute back to type="password" from typee="text"

Upvotes: 1

Views: 5045

Answers (1)

charlietfl
charlietfl

Reputation: 171669

You are setting the attribute inside the if() not getting it so you can check it's value

Instead try doing something like:

// get the attribute value
var type = $(inputField).attr("type"); 
// now test it's value
if( type === 'password' ){
  $(inputField).attr("type", "text");
}else{
  $(inputField).attr("type", "password");
} 

Note the difference ... you set when second argument is provided and get when it is not

Upvotes: 3

Related Questions