Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Focusing first control in the form using jquery

Tags:

jquery

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".

like image 373
Zakaria Avatar asked Nov 06 '08 04:11

Zakaria


People also ask

How do you focus an element in jQuery?

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.

How do I set focus on first textbox?

Set the focus to the first input box. JavaScript Code: $( document ). ready(function() { $( "#field1" ).

How do I set the focus to the first form field?

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.

What is focus function in jQuery?

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.


2 Answers

$('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.

like image 164
nickf Avatar answered Oct 07 '22 00:10

nickf


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.

like image 36
Zakaria Avatar answered Oct 07 '22 00:10

Zakaria