0

I have written some code to remove the input placeholder text and it works as expected. The problem I have is how do I reset the value of placeholder after it has been removed?

const input = document.getElementById('input');

if (input.placeholder) {
  input.addEventListener('focus', (e) => {
    input.placeholder = '';
  });
} else {
  input.placeholder.preventDefault()
};
<div class="mainInput">
  <input type="text" class="input" id="input" placeholder="Enter your todo : ">
  <button class="btn" id="btn">Submit</button>
</div>
<span> Todo list : </span>
Fraser
  • 15,275
  • 8
  • 53
  • 104
rabie
  • 1
  • 1
  • 2
  • 5
    What do you mean by "reset"? Why do you remove the placeholder in the first place? – Nico Haase Dec 21 '20 at 12:47
  • use remove attribute function on load : input.removeAttribute("placeholder"); – Shantun Parmar Dec 21 '20 at 12:48
  • @NicoHaase Yes there is no need to remove the placeholder. – dhruw lalan Dec 21 '20 at 12:49
  • 2
    By default any placeholder text is removed as soon as you start typing in the input - when you clear the input it is "reset" (placeholder text reappears). I am really not sure what you are trying to achieve here beyond the default behaviour – Fraser Dec 21 '20 at 12:50
  • 1
    if you just want to hide the placeholder then this is the solution you are looking for https://stackoverflow.com/questions/9707021/how-do-i-auto-hide-placeholder-text-upon-focus-using-css-or-jquery – Swaraj Gandhi Dec 21 '20 at 12:57

1 Answers1

0

I think this solution should work for you!

It will just reset your placeholder value.

const input = document.getElementById('input');

if (input) {
   // it will remove placeholder value on focus and store with dataset variable
  input.addEventListener('focus', (e) => {
    input.dataset.placeholder = input.placeholder
    input.placeholder = '';
  });
    
  // it will reset placeholder value on blur by dataset variable
  input.addEventListener('blur', (e) => {
    input.placeholder = input.dataset.placeholder;
  });
}else{
  console.log("input is not defined",input);
}
<div class="mainInput">
  <input type="text" class="input" id="input" placeholder="Enter your todo : ">
  <button class="btn" id="btn">Submit</button>
</div>
<span> Todo list : </span>
Dhiraj
  • 1,119
  • 1
  • 13
  • 23