简体   繁体   中英

Why isn't attr working in jquery for input?

Here is my code and I have no Idea why my the password type isn't changing... tnx for reading.

 $('.btn-show-pass').click( function(){ $(this).find('i').toggleClass("fa-eye fa-eye-slash"); var input = $($(this).attr("toggle")); input.attr("type", "text"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span toggle='#passInput' class="btn-show-pass"><i class="fa fa-eye" aria-hidden="true"></i></span> <input id='passInput' class="input100" type="password" name="password">

To toggle between the input types, you could adjust your code like this:

 $('.btn-show-pass').click(function() { $(this).find('i').toggleClass("fa-eye fa-eye-slash"); var input = $($(this).attr("toggle")); if (input.attr("type") == "password") { input.attr("type", "text"); } else { input.attr("type", "password"); } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <span toggle='#passInput' class="btn-show-pass">click<i class="fa fa-eye" aria-hidden="true"></i></span> <input id='passInput' class="input100" type="password" name="password">

Update: As mentioned in the comments, to toggle between the input types was not the real problem. The problem was that the code didn't work on the website. This was caused by an older jQuery version that did not allow to change the type of the input from password to text. Upgrading to a newer jQuery version solved the issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM