Clear input when user starts writing

Asked

Viewed 783 times

2

Good afternoon, maybe there is already this answer or this question. However I did not find here or in google as I need. I found several scripts to delete the field of an html form when the user clicks(Focus) on a given input, but what I need is for the field with the original text to be deleted only when the user starts writing...

someone can help me?

thank you

  • And how do you differentiate "start writing" from a normal input? In other words, if you already have content, how long does it take to be considered "start"? The fields are already filled in, is that it? in this case a placeholder would be more correct. Explain a little better and join code to understand your problem.

  • @Sergio, the fields are already written... type: <input value="name"/> ... when the user writes the first letter, this value "name", is deleted...

  • 1

    Andrei, have you tested using a placeholder? -> <input placeholder="nome" />

  • No... I’m gonna test

  • 1

    @Sergio, thank you very much! I hadn’t even heard of it... Hug!

  • 1

    Andrei, great, I’ll add an answer to that

Show 1 more comment

2 answers

6


The natural/modern solution for this is using placeholder.

 <input placeholder="nome" />

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

If you want to use the keydown, that is when the user starts writing, you can do so by comparing the value attribute with the real value that he has at the moment:

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: http://jsfiddle.net/hh7qqrd7/

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

1

This is very simple to do with HTML5, just add a placeholder in his input or textarea, take the 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 only accepted in IE 10+

See here the support: http://caniuse.com/#feat=input-placeholder

Browser other questions tagged

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