A simple example of a jQuery text box losing or gaining focus

  • 2020-03-30 01:48:49
  • OfStack

Version of a

CSS code section:


.focus { 
     border: 1px solid #f00;
     background: #fcc;
} 

When the focus is obtained, add the focus style, add the border, and change the background color to # FCC

HTML code section:


<body>
    <form action="" method="post" id="regForm">
        <fieldset>
            <legend> Basic personal information </legend>
                <div>
                    <label  for="username"> The name of the :</label>
                    <input id="username" type="text" />
                </div>
                <div>
                    <label for="pass"> password :</label>
                    <input id="pass" type="password" />
                </div>
                <div>
                    <label for="msg"> The detailed information :</label>
                    <textarea id="msg" rows="2" cols="20"></textarea>
                </div>
        </fieldset>
    </form>
</body>

There are two inputs, a textare box.

:input matches all input, textarea, select, and button elements.

JQuery code part:


<script type="text/javascript">
    $(function(){
        $(":input").focus(function(){
              $(this).addClass("focus");
        }).blur(function(){
              $(this).removeClass("focus");
        });
    })
    </script>

Match all input elements with :input. When getting focus, add style focus and automatically identify the current element with $(this). The focus() method is a function that gets the focus event when it happens. The blur() method is a function that is executed when a loss of focus event occurs.

Version 2:

Sometimes the text box has the default content as a prompt to get focus and then make it go away. The following modifications can be made:


<script type="text/javascript">
    $(function(){
        $(":input").focus(function(){
              $(this).addClass("focus");
              if($(this).val() ==this.defaultValue){  
                  $(this).val("");           
              } 
        }).blur(function(){
             $(this).removeClass("focus");
             if ($(this).val() == '') {
                $(this).val(this.defaultValue);
             }
        });
    })
    </script>

Make a logical decision to empty the text box if the value is the default.

Lost focus, if the text box is empty, that is, there is no input, the value is set to the default value.

This is a simple logic.


Related articles: