Is there a simple way to set the focus (input cursor) of a web page on the first input element (textbox, dropdownlist, ...) on loading the page without having to know the id of the element?
I would like to implement it as a common script for all my pages/forms of my web application.
To set focus to an HTML form element, the focus() method of JavaScript can be used. To do so, call this method on an object of the element that is to be focused, as shown in the example. Example 1: The focus() method is set to the input tag when user clicks on Focus button.
The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.
Although this doesn't answer the question (requiring a common script), I though it might be useful for others to know that HTML5 introduces the 'autofocus' attribute:
<form> <input type="text" name="username" autofocus> <input type="password" name="password"> <input type="submit" value="Login"> </form>
Dive in to HTML5 has more information.
You can also try jQuery based method:
$(document).ready(function() { $('form:first *:input[type!=hidden]:first').focus(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With