Skip to content Skip to sidebar Skip to footer

Javascript To Replace All The Input.value By '*' Like A Password Typing

I have a And while doing the keypress, directly with js code, it replaces all the characters for '*'. Li

Solution 1:

Why do you need JavaScript to accomplish what HTML gives your for free? The element exposes all the same attributes/properties so you can still use it like a text box.

<inputtype="password">

If you feel you must reinvent the wheel, this can be done by using two fields. The user will type in the first and it will display the mask character and the actual key will be stored in a hidden input field for processing:

// Get references to DOM elements:var txt = document.getElementById("txtMask");
var hdn = document.getElementById("pass");

// This keeps track of how many characters should be displayedvar maskLen = 1;

// Set up input event on first box
txt.addEventListener("keydown", function(evt){

  // Manually put the right amount of mask characters into the box// and update the maskLen valuevar str = '#'.repeat(maskLen++)
  this.value = str;
  
  // Cancel the event and stop bubbling
  evt.preventDefault();
  evt.stopPropagation();
  
  // Set the actual typed data into the hidden field
  hdn.value += evt.key;

  // Just for testing:console.clear();
  console.log("Actual data is: " + hdn.value);
  
});
<inputtype="text"id="txtMask"autocomplete="false"><inputtype="hidden"id="pass">

Post a Comment for "Javascript To Replace All The Input.value By '*' Like A Password Typing"