How to remove default value of input on focus

2019-03-10 16:57发布

I have an input box that has default value text assigned to it. How can I remove this text when the user focuses on the field::

CoDE

<input type="text" name="kp1_description" value="Enter Keypress Description">

9条回答
对你真心纯属浪费
2楼-- · 2019-03-10 17:52

With HTML5 you could do it without Javascript: just use placeholder instead of value. I think it's a nice addition, but of course you need to check the browser compatibility first.

查看更多
爷、活的狠高调
3楼-- · 2019-03-10 17:52

HTML:

<form method="post">
  <input type="text" id="customer" value="Username"/>      
  <input type="Submit" value="Login" class="rc" />
</form>

Javascript code:

<script>
$('#customer').on({
    focus:function(){                   
      if(this.value == 'Username') this.value = '';
    },
    blur:function(){
      if(this.value == '') this.value = 'Username';
    }
})
</script>

That's all, I hope it'll help.

查看更多
Luminary・发光体
4楼-- · 2019-03-10 17:53

Plain JavaScript:

(function () {
  let input = document.querySelector ("input[name='kp1_description']");
  input.onfocus = function () {
    this.placeholder = this.value;
    this.value = '';
  };
})();

This keeps the value in the placeholder instead of removing it completely. If you do not like this, remove the placeholder line.

查看更多
登录 后发表回答