Good afternoon, there is the following code:

<div class="group-box"> <input type="password" id="password-show" class="modal-input" placeholder="Пароль"> <button type="button" class="show-password"><img src="img/show-password.png" alt="show-pass" /></button> </div> 

And the following jQuery code:

 $('button.show-password').click(function() { if($('#password-show').attr('type').val() == 'password') { $('#password-show').attr('type').val() = 'text'; } else { $('#password-show').attr('type').val() == 'text'; } }); 

For some reason it does not work. Uncaught TypeError error occurs: $ (...). Attr (...). Val is not a function

What am I doing wrong?

  • In elsewhere, two is equal, that is, verification instead of assignment - Mr. Black

1 answer 1

The attr () method, if not passing the second parameter, returns the value of the attribute specified in the first parameter. This is a string value and the val () method is not allowed to it. If you need to change the value of a specific attribute, then this value is passed to the second parameter of the attr () method:

 var pass = $('#password-show'); $('button.show-password').click(function() { pass.attr('type', pass.attr('type') === 'password' ? 'text' : 'password'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="group-box"> <input type="password" id="password-show" class="modal-input" placeholder="Пароль"> <button type="button" class="show-password"> <img src="img/show-password.png" alt="show-pass" /> </button> </div>