…and corresponding (X)HTML markup (abbreviated for clarity):
<form> <input id="element" /> <input /> <input /> </form>
In this example, the first form element (identified by
id="element") will be automatically focused when the document loads, thus facilitating the process of entering data in the form. This technique would serve users well on login pages (wink, wink;), or anywhere forms are required on a repetitive basis.
..and here is a “live” example:
..and corresponding code:
<input onfocus="this.select();" value="Select this element to highlight text.." type="text">
The method discussed in this article doesn’t work as expected in newer versions of Chrome. If that sounds like you, try this snippet instead:
<input onclick="this.select()" type="text" value="Select this element to highlight text..">
So to see that working in Chrome, try the demo:
Let me know if this technique stops working in a future version of Chrome.
Couple of modified/hybrid functions sent in by Grant Richardson:
“Just a quick but huge thanks for the post. This may seem simple to you, but I searched for 2 hours but couldn’t find anywhere how to set autofocus on woocommerce login form, so I used your code and GasGiant’s suggestion in the comments to put this together. Other methods I found didn’t work. I want to give back by sharing my solution to you. Please consider sharing for others in my situation who may need it. The following code goes in child theme’s functions.php or via a custom functions plugin:”
“Here’s an updated version of the code snippet to share if you like. This version checks first to see whether the user is logged out and is on the woocommerce my-account page.”
Since I use a common header for a number of PHP pages, some pages have forms while others do not. To keep from throwing an error on the pages where the element does not exist, I enclosed the
focus()action inside an
Excellent tip – Thank you for sharing!
Thank u very much for this logic and code. I was searching for it and just found @ this place. thank u very much. i gonna use your code for my software. thankz once again.
My pleasure — happy to help ;)
you can also always select the first element of the form:
this way you don’t need to know the id of the first element
if you want to get the form and you just have one form:
var aForm = document.forms;
Sweet tip, Hephaistus — thanks!