Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: toggle plain text to hide it like password text on click of a button

I do not have a <input> or any form. I want some way to toggle a plain text to something like **** on click of a button.

for example I have

<p id='one'>google_yahoo</p>
<button id='two'>toggle</button>

so when I click the button once, <p> should become:

<p>************</p>

Then when I click the button then I should again get back google_yahoo
But by default I want it be in ***** form.

What I did:

<script>
  function myfunction(){
  $("#two").click(function(){
  $("#one").text("abc");
  });
  };
</script>


Any straightforward, easy to understand solution anyone?

like image 799
pyofey Avatar asked Oct 19 '25 14:10

pyofey


1 Answers

You need to create some variables to store value of your text. Try it on JSFiddle.

var txt = document.getElementById('one');
var btn = document.getElementById('two');
var visible = 1;
var value = '';

btn.addEventListener('click', function(){
  if(visible){
    value = txt.innerHTML;
    txt.innerHTML = '*'.repeat(value.length);
  }else{
    txt.innerHTML = value;
  }

  visible = !visible;
});

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!