Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery, set focus on the first enabled input or select or textarea on the page

It's fairly straightforward. I want to set focus to the first enabled and not hidden control on the page.

For a textbox, I have

$("input[type='text']:visible:enabled:first").focus();

But I want to get "all" form input controls: textbox, checkbox, textarea, dropdown, radio in my selector to grab the first enabled and not hidden control. Any suggestions?

like image 331
Josh Avatar asked Dec 01 '10 19:12

Josh


People also ask

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.

How do you focus an input element on page load?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.

How can input focus in jQuery?

Using jQuery With jQuery, you can use the . focus() method to trigger the “focus” JavaScript event on an element. This method is a shortcut for . trigger("focus") method.

How Stop focus in jQuery?

In jQuery by using blur() property we can remove focus from input textbox field.


3 Answers

$(':input:enabled:visible:first').focus(); 
like image 77
Jordan Ryan Moore Avatar answered Oct 12 '22 11:10

Jordan Ryan Moore


As an extension of Jordan's answer

$(':input:enabled:visible:not([readonly]):first').focus();

This one also excludes readonly inputs

like image 27
Dmitri Tsoy Avatar answered Oct 12 '22 10:10

Dmitri Tsoy


This is a little more comprehensive:

$('form :input:text:visible:not(input[class*=filter]):first').focus();

Lamen: Focus the cursor in the first text input in a form that is visible, but if it use the class named "filter", ignore it!

like image 40
zmonteca Avatar answered Oct 12 '22 10:10

zmonteca