Clear input when user starts typing

2

Good afternoon, maybe this answer or this question already exists. But I did not find it here or google the way I need it. I found several scripts to delete the field of an html form when the user clicks on a particular input, however, what I need is for the field with the original text to be deleted only when the user starts typing ...

Can anyone help me?

Thank you

    
asked by anonymous 08.09.2015 / 17:53

2 answers

6

The natural / modern solution to this is using placeholder .

 <input placeholder="nome" />

However placeholder is HTML5 and some older browsers do not support. How to do it then? here is an alternative:

If you want to use keydown , that is when the user starts typing, you can do this by comparing the value attribute with the actual value it currently has:

var input = document.querySelector('input');
input.addEventListener('keydown', function (e) {
    var original = this.getAttribute('value');
    var novo = this.value;
    if (novo == original) this.value = '';
});

jsFiddle: link

The .getAttribute('value'); is always the same as in HTML. What is dynamic and changes according to what is written is the .value property. So you can know if what's in the input is still the original.

    
08.09.2015 / 18:05
1

This is very simple to do with HTML5 , just add a placeholder to your input or textarea , see example:

<span>Nome</span>
<br>
<input type="text" placeholder="Digite seu Nome">
<br>
<br>

<span>Mensagem</span>
<br>
<textarea placeholder="Digite sua Mensagem"></textarea>

Simple like that!

Unfortunately it is only accepted in IE 10+

See the support here: link

    
08.09.2015 / 18:00