Search code examples
javascriptformsjoinconcatenation

How can one make <input> to show *** instead as plain text


I want id=demo (/document.getElementById("demo").innerHTML) for the value myInput3 to output like ****.

The current behaviour shows the value of myInput3 in plain text.

i.e. If I enter abcd1234 in myInput3, I want to see ******** in id=demo

<script>

function myFunction() {
  var x = document.getElementById("myInput").value + ' ' + document.getElementById("myInput2").value + ' ' + document.getElementById("myInput3").value;
  document.getElementById("myInput3").value;
  document.getElementById("demo").innerHTML = "Your details are: " + x;
}


</script>

<p>Write something in the text field to trigger a function.</p>

<div>Name:</div> <div><input type="text" id="myInput" oninput="myFunction()"></div>
<div>Username:</div> <div><input type="text" id="myInput2" oninput="myFunction()"></div>
<div>Password:</div> <div><input type="password" id="myInput3" oninput="myFunction()"><div>

<p id="demo"></p>


Solution

  • You can repeat the character (*) up to the length of the character in the password field using repeat():

     var pass = document.getElementById("myInput3").value.trim();
     pass = '*'.repeat(pass.length);
    

    <script>
    
    function myFunction() {
      var pass = document.getElementById("myInput3").value.trim();
      pass = '*'.repeat(pass.length);
      var x = document.getElementById("myInput").value + ' ' + document.getElementById("myInput2").value + ' ' + pass;
      document.getElementById("myInput3").value;
      document.getElementById("demo").innerHTML = "Your details are: " + x;
    }
    
    
    </script>
    
    <p>Write something in the text field to trigger a function.</p>
    
    <div>Name:</div> <div><input type="text" id="myInput" oninput="myFunction()"></div>
    <div>Username:</div> <div><input type="text" id="myInput2" oninput="myFunction()"></div>
    <div>Password:</div> <div><input type="password" id="myInput3" oninput="myFunction()"><div>
    
    <p id="demo"></p>