最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - remove placeholder attribute on focus in plain JS (non-jQuery) - Stack Overflow

programmeradmin3浏览0评论

I would simply like to remove the attribute with my if condition and add it back with my else.

function onFocusChange () { 
  if (document.getElementById("input").focus()) { 
     document.getElementById("input").placeholder = "";
   else { 
     document.getElementById("input").placeholder = "This is Placeholder Text";   
   }
  }
}

mark-up:

<label for="input">
  Question #1:
</label>
<input type="text" id="input" name="Address" required="required" placeholder="This is Placeholder Text" />

I would simply like to remove the attribute with my if condition and add it back with my else.

function onFocusChange () { 
  if (document.getElementById("input").focus()) { 
     document.getElementById("input").placeholder = "";
   else { 
     document.getElementById("input").placeholder = "This is Placeholder Text";   
   }
  }
}

mark-up:

<label for="input">
  Question #1:
</label>
<input type="text" id="input" name="Address" required="required" placeholder="This is Placeholder Text" />
Share Improve this question edited Jan 19, 2018 at 16:31 Lieutenant Dan asked Jan 19, 2018 at 16:21 Lieutenant DanLieutenant Dan 8,29828 gold badges97 silver badges215 bronze badges 3
  • 1 "For demo purposes..." your question does not show any research effort. – tao Commented Jan 19, 2018 at 16:24
  • 1 ... and this. – PM 77-1 Commented Jan 19, 2018 at 16:26
  • 1 Why remove it when browser does it? – epascarello Commented Jan 19, 2018 at 16:31
Add a ment  | 

2 Answers 2

Reset to default 4

To remove attribute you can use element.removeAttribute("placeholder");

You can use focus & blur event

var element = document.getElementById('input');
element.addEventListener('focus', function() {
  element.setAttribute('placeholder', '')

})

element.addEventListener('blur', function() {
  element.setAttribute('placeholder', 'This is Placeholder Text')

})
<label for="input">
  Question #1:
</label>
<input type="text" id="input" name="Address" required="required" placeholder="This is Placeholder Text" />

发布评论

评论列表(0)

  1. 暂无评论