How to "hide" a password in html text input

Viewed 170

I am currently building a form, where I have a password.

Is a way to maintain the input type as text while the password remains "hidden".

So basically instead of this being displayed in the text field:

mypassword

I want it to say:

*********

or something close to that. So basically just making the text that the user inputs not to be visible.

I know that changing the type to password will be a solution but I need to maintain the type as text.

1 Answers

One reason why this could be useful is temporarily show last entered character as on mobile devices:

function passwordInput(el)
{
  //already initialized?
  if (el.actualValue !== undefined)
    return el;

  let timer = null;
  el.actualValue = el.value;
  el.addEventListener("input", e =>
  {
    clearTimeout(timer);
    const val = el.value,
          start = el.selectionStart,
          end = el.selectionEnd,
          len = val.length - el.actualValue.length,
          //find none-hidden characters
          diff = (val.substring(0, start).match(/[^●]+/g)||[""])[0],
          //this will be shown for nn seconds
          last = diff === "" ? "" : diff[diff.length - 1],
          //replace all characters with hidden character
          vis = "".padStart(val.length, "●");

    //record new value
    el.actualValue = el.actualValue.substring(0, start - diff.length) + diff + el.actualValue.substring(start - len);
    //replace visible value with hidden characters, except for the last "new" character
    el.value = vis.substring(0, start - last.length) + last + vis.substring(start);
    //set cursor back to it's original position
    el.selectionStart = start;
    el.selectionEnd = end;
    //hide entire visible value after nn seconds
    timer = setTimeout(() =>
    {
      const start = el.selectionStart,
            end = el.selectionEnd;

      el.value = vis;
      el.selectionStart = start;
      el.selectionEnd = end;
    }, 1000); // 1 second delay
  });
  if (el.value !== "")
    el.dispatchEvent(new Event("input"))

  return el;
}

passwordInput(document.getElementById("myInput")).addEventListener("input", e =>
{
  //display real value
  output.textContent = e.target.actualValue;
});
<input type="text" id="myInput" autocomplete="off">
<div>Actual value: <span id="output"></span><div>

Basically, what it does, is store actual value in inputElement.actualValue property and replaces value with "●" character. There is one kink I didn't bother to look at, is selection getting reset when last character become hidden.

Related