Using jquery how do I focus the first element (edit field, text area, dropdown field, etc) in the form when the page load?
Something like:
document.forms[0].elements[0].focus();
but using jquery.
Another requirement, don't focus the first element when the form has class="filter".
The focus() is an inbuilt method in jQuery which is used to focus on an element. The element get focused by the mouse click or by the tab-navigating button. Here selector is the selected element. Parameter: It accepts an optional parameter “function” which specifies the function to run when the focus event occurs.
Set the focus to the first input box. JavaScript Code: $( document ). ready(function() { $( "#field1" ).
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.
jQuery focus() Method The focus event occurs when an element gets focus (when selected by a mouse click or by "tab-navigating" to it). The focus() method triggers the focus event, or attaches a function to run when a focus event occurs. Tip: This method is often used together with the blur() method.
$('form:not(.filter) :input:visible:enabled:first').focus()
This will select the first visible input element (<input />
, <select>
, <textarea>
) that doesn't have the class filter
in it.
For the background I used the script in ruby on rails app. After trying all your answer and found out they all doesn't works, With a search on google i found this snippet that works:
$(function() { $("form:not(.filter) :input:visible:enabled:first").focus(); });
It turn out $('form :input:first')
match the hidden input that rails insert on every form.
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