The jQuery :focus selector selects all the elements that are currently focused on. There are many elements inside the form. However, when you have to select only the elements which have focus, you have to use this selector as given in the example below.
Syntax of the Selector
The syntax of jQuery :focus selector is given below.
The selector requires no arguments to pass with it to use. However, if you want to select only the specified element, you have to specify the tag name, class, or id of the element. If the form contains a single element, you don’t have to specify the tag name with the selector.
jQuery :focus Selector Selects All Focused Elements
If you want to select focused elements in a form, you have to use this selector. If the form contains more than one input, it focuses the last input element. See the example given below to find the focused element using this selector.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<script> $(document).ready(function(){ $("input").focus(); $( ".mydformfocus :focus" ).css("background", "yellow"); }); </script> <form action="#" class="mydformfocus"> <label>Name</label> <input type="text" name="name" placeholder="Enter your name..."><br><br> <label>Email</label> <input type="email" name="email" placeholder="Enter your email..."><br><br> <button type="button" name="submit">Submit</button> </form> |
Output
The above example showing the single element as the focused element. It’s the last input element of the form. jQuery applies the background color as ‘yellow’ to the element. You can apply other effects to the input elements using this selector.
I hope you like this tutorial post of jQuery :focus selector. If you have any queries regarding this tutorial post, please comment below.
Also tell me, what other methods you are using with the selector by commenting below.
References