How to clear text field on focus of text field

前端 未结 9 1937
悲&欢浪女
悲&欢浪女 2020-12-29 12:15

I want to clear the text field when the user clicks on that

相关标签:
9条回答
  • 2020-12-29 12:55

    Or you can simply use the placeholder attribute For example<input name="name" type="text" id="input1" size="30" maxlength="1000" placeholder="Enter Postcode or Area"/>

    0 讨论(0)
  • 2020-12-29 13:01

    Add a following script to your js file:

    var input1 = document.getElementById("input1")
    
    input1.onfocus = function() {
      if(input1.value == "Enter Postcode or Area") {
          input1.value = "";
      } 
    };
    
    input1.onblur = function() {
        if(input1.value == "") {
           input1.value = "Enter Postcode or Area";
       } 
     };
    
    0 讨论(0)
  • 2020-12-29 13:03

    You can use <input ... onfocus="this.value='';"/>.

    This way, the field will be cleared when it gains focus. However, if you only want to clear it when user clicks on it (i.e. not when the field gains focus with the keyboard for example), then use onclick instead of onfocus.

    However, as pointed by David Dorward in a comment, this behavior may not be expected by the user. So be careful to set this feature on really specific fields (such as search field).

    0 讨论(0)
提交回复
热议问题