jQuery set focus method
The focus() method can be used to set the focus to an element of HTML. This usually requires while filling a form and then notifying a user about the certain action to take in order to correct input field.
Example of using set focus method
In the following example, the focus is set in the document.ready() event of jQuery. The demo page contains two forms fields that are textboxes. By using the focus method, the focus is set to the second textbox as web page loads:
Have a look by clicking the link or image below:
Experience this example online
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
<html>
<head>
<script src=“http://code.jquery.com/jquery-1.10.1.min.js”></script>
<script>
$(document).ready(function(){
$(“#txtfocus”).focus();
});
</script>
</head>
<body>
<input type=“text” id=“txtfocus2”><br/>
This text box is set focused: <input type=“text” id=“txtfocus”>
</body>
</html>
|
Experience this example online
You see, we simply used the
1
|
$(“#txtfocus”).focus();
|
inside the document.ready() where txtfocus is the ID of the second textbox. Similarly, you may set focus to any HTML element upon certain user action like clicking a button, link or pressing the submit button etc.
Useful reading: jQuery focus method()
Leave A Comment?