简体   繁体   中英

How to operate with onfocus?

I have a textbox.

Now when the page is opened i want the textbox to have a default value.Once he click on the textbox the value should disappear and again when he removes his cursor from the text box ,the old value should come back.

So how do i do this ?

Thanks

Add a specific class to all textboxes on the page that you want to have this functionality.

Then, use this code to apply the functionality to the elements that have the class:

window.onload = function() {
   var elements = document.querySelectorAll('.yourClassName');
   for(var i = 0, j = elements.length; i < j; i++) {
      var element = elements[i]; 
      element.onfocus = function() {
         this.value = '';
         this.style.color = 'black';
      };
      element.onblur = function() {
          if(this.value == '') {
             this.value = this.getAttribute('defaultValue');
             this.style.color = 'grey';
          }
      };
      element.onblur();
   }
};
​

Working example: http://jsfiddle.net/6TmGA/1/

Can you use jQuery?

If you can there are a lot of plugins that will help with this.

such as;

http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/

<script language="JavaScript">
    function setFocus() {

           document.getElementById('username').focus();

    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM