Make input disappear when I click on it again

Viewed 160

How do I make it so that when I enter something in an input field, and I unselect/click out of the field and then click on the input field again the text/input I wrote disappears?

4 Answers

You can add the focus listener to the input and clear the value everytime that event is launched.

Fiddle link: https://jsfiddle.net/dfa6m42e/1/

let inp = document.querySelector('#myInput')

inp.addEventListener('focus', () => {
  inp.value = '';
})
<input type="text" id='myInput'>

I am not sure that you need to have a blur event. You can add something like this wherever you are initiating your event listeners.

var inputElement = document.getElementById("myinputelement");
inputElement.addEventListener("focus", function(e) {
  this.value="";
})

How about this?

let input = document.querySelector('input');
input.onclick = function(){ input.value = ''; };

You can use the blur event to add a focus event

var myInput = ...;
myInput.addEventListener("blur", function(e) {
  myInput.removeEventListener("blur", this);
  myInput.addEventListener("focus", function(e) {
    myInput.value = "";
  }
}
Related