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
Use an
if/then
statement. When you toggle the content, you can save the old contents with.data()
.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 betweenpassword
andtext
.An alternative (and easier to implement) solution is to include both visible and obscured password in the HTML initially, eg:
Of course, this may not fit your scenario if the password is only a variable – in that case I’d do
just before the .toggle, or in doc.ready, or after it’s set if loading via ajax etc.
Alternatively, if you really want to use
.toggle()
: