How to work with onfocus?

I have a text box.

Now that the page is open, I want the text box to have a default value. When he clicks on the text field, the value should disappear, and again, when he removes the cursor from the text field, the previous value is returned.

So how do I do this?

thank

+3
source share
3 answers

Add a specific class to all the text fields on the page that you want to use.

Then use this code to apply functionality to elements that have a 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/

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

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

    }
</script>
0

Source: https://habr.com/ru/post/1766698/


All Articles