JQuery Selector focus

From CoderLearner
Jump to: navigation, search

Description

Trigger event whenever the element is focus.

Syntax

$('element').focus(function(){

});

Example 1

When mouse focus on the input element, it changes the element background color. When mouse move from focus to blur, it will change the element background back to white.

<html>
   <head>
      <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
      <title>Select</title>
      <script 
         type="text/javascript" 
         src="/lib/jquery-1.7.2.min.js">				 
      </script>
      <script>
         $().ready(function() {
            $('form#mmm input[type="text"]').focus(function(){
               var txt_name=$(this).attr("name");
               $('div#msg').text('Focus: ' +txt_name);
               $(this).css('background-color','green');
            }).blur(function(){
               $(this).css('background-color','white');
            });
         });
      </script>
   </head>
   <body> 
      <div id="msg"></div>
      <form id="mmm">
         <table border="0">
            <tr>
               <td>First Name:</td>
               <td>
                  <input type="text" name="first_name" size="20" maxlength="20"/>

               </td>
            </tr>
            <tr>
               <td>Middle Name:</td>
               <td>
                  <input type="text" name="middle_name" size="20" maxlength="20"/>
               </td>
            </tr>
            <tr>
               <td>Last Name:</td>
               <td>
                  <input type="text" name="last_name" size="20" maxlength="20" />
               </td>
            </tr>

            <tr>
               <td colspan="2">
                  <input type="submit" name="register" value="Register" />

               </td>
            </tr>
         </table>
      </form>
   </body>
</html>

Try It