skip to Main Content

How to toggle between the old and new html value in jQuery?

html

<span id="Password">••••••••••</span> 
<i class="fa-regular fa-eye passw"></i>

jQuery

$(".passw").click(function(){
  var passw = "12345678";
  //$("#Password").toggle.html(passw);
  $("#Password").html.toggle(passw);
});

3

Answers


  1. Use an if/then statement. When you toggle the content, you can save the old contents with .data().

    $(".passw").click(function() {
      var passw = "12345678";
      $("#Password").html(function(i, oldhtml) {
        if (oldhtml == passw) {
          return $(this).data("saved-pass");
        } else {
          $(this).data("saved-pass", oldhtml);
          return passw;
        }
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    Password: <span id="Password">&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;</span>
    <i class="fa-regular fa-eye passw">Toggle</i>

    Note that most sites use an <input type="password"> for entering passwords, not a span. To reveal and hide the password they toggle the type between password and text.

    Login or Signup to reply.
  2. An alternative (and easier to implement) solution is to include both visible and obscured password in the HTML initially, eg:

    $("#password-toggle").on("click", () => {
        $("#Password,#Password-Obscured").toggle();
    });
    <span id="Password" style='display:none'>P4$$w0rd</span> 
    <span id="Password-Obscured">&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;</span> 
    <br/><button type='button' id="password-toggle">toggle password</button>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    Of course, this may not fit your scenario if the password is only a variable – in that case I’d do

    $("#Password").text(pwd)
    

    just before the .toggle, or in doc.ready, or after it’s set if loading via ajax etc.

    Login or Signup to reply.
  3. Alternatively, if you really want to use .toggle():

    $('#Password').click(function(){
      $(this).toggle();
    });
    #Password {
      font-size: 16px;
      user-select: none;
      cursor: pointer;
    }
    
    #Password[style="display: none;"] {
      display: inline!important;
      font-size: 0;
    }
    
    #Password[style="display: none;"]:before {
      content: attr(data-password);
      font-size: 16px;
    }
    Test <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <span id="Password" data-password="0123456789">&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;&#x2022;</span> test
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search