Replace an input value and keep the previous value

Asked

Viewed 696 times

2

I need a input[type="text"], in which the user writes anything ("abc", for example), but in the visual appears other symbols, but keeping the previous value when picked up by Javascript or sent in a form (as in a input[type="password"]).

Would that be possible?

Thank you in advance.

  • 2

    What have you tried so far? Enter the code to see and tell you what you need to adjust or correct

2 answers

1

The simplest way is to use CSS -webkit-text-security

You can use the values none, square, circle or disc.

Example below using circle:

    function Foo() {
    	frm = document.getElementById("frm");
    	document.getElementById("bar").innerHTML = frm["foo"].value;
    	//console.log(frm["foo"].value);
    }
input.foo { -webkit-text-security: circle; }
    <form id="frm" action="" method="POST">
    <input type="text" name="foo" class="foo" size="15">
    <input type="button" value="clique para ver o texto real" onclick="Foo();">
    </form>
    
    <br><div id="bar"></div>
    

The Javascript part is for didactic testing only, to display the actual text.

0

In javascript, something manual is to replace the characters by others radorically as the user type and store the original value. Could be more or less like:

var textoOriginal = '';
var entrada = document.getElementById("entrada");

function embaralhar(event) {
  var x = event.which || event.keyCode;
  if (x !== 8) { 
    textoOriginal += entrada.value.substr(entrada.value.length - 1);

    entrada.value = entrada.value.replaceAt(entrada.value.length -1, randomico());
  }
};

function exibir() {
  document.getElementById("texto").innerHTML = textoOriginal;
};

function limpar() {
  textoOriginal = '';
  document.getElementById("texto").innerHTML = '';
  document.getElementById("entrada").value = '';
};

function randomico() {
  var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  return possible.charAt(Math.floor(Math.random() * possible.length));

}

String.prototype.replaceAt = function(index, character) {
  return this.substr(0, index) + character + this.substr(index + character.length);
}
<input id="entrada" type="text" onkeypress="embaralhar(event)" />
<label id="texto">
  <br/>
  <br/>
<button id="exibir" onClick="exibir()">Exibir Original
<button id="limpar" onClick="limpar()">Limpar</button>

It is an example. For a real case, it is important to validate if the user deletes some value, deletes it through selection, etc.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.