Introduction:

In this article we will explain how to set focus of form elements like <input>, <select> etc. in jquery or What is focus() method in jquery or why use focus() method in jquery with example.

Description:

The jQuery focus() event occurs when an element get focus. It is trigger by a mouse click or by tab-navigating to it.

This event is used to some limited sets of elements such as form elements like <input>, <select> etc. and links <a href>. The focused elements are usually highlighted in some way by the browsers.

The focus method is often used together with blur () method.

Syntax:

$(selector).focus()

Example of jQuery focus () method

Let's take an example to demonstrate jQuery focus() Method.

 

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>    <title>Example of jQuery </title> <script src="Scripts/jquery-1.7.1.min.js"></script>    <script type="text/javascript">        $(document).ready(function () {
     $("button").click(function () {
        $("#txtname").focus();               
     });        });    </script>    </head>
<body>    
    <button>Click To Focus</button><br><br>     <input type="text" id="txtname" />    
</body>
</html>

 

OutPut:


In above example we have a “textbox” and button when we click on button then our cursor will be focus on “textbox”.

 

focus() - Using Callback function


<script>       
$(document).ready(function () {       
    $("#txtname").focus(function () {
       $(this).css("background", "red");             });        });    </script>

 

I hope this article will help to you.

0 comments


Leave a comment

Make sure you enter the (*) required information where indicated. HTML code is not allowed.

Welcome to SQL Tutorials Point

Don't have an account? Click here to Create a new account, it takes less than a minute.