Sencer H.
Sencer H.

Reputation: 1271

jquery focus() just focusing to first text input

I have a HTML file included multi forms. I'm trying to focus first element of the 2nd form on page loaded. I was added jquery code to end of HTML to focus first input of the form:

<script>
    $("form[id=form2]").find("input[type!=hidden]:first").focus();
</script>

It works well if first element of the 2nd form is text input, but it is not working if its dropdown or checkbox. How can I make this focus to any first element?

EDIT: I need to use ID in form selector, because of the form ID can be variable.

Upvotes: 0

Views: 526

Answers (2)

adeneo
adeneo

Reputation: 318342

$("form:eq(1) :input[type!='hidden']").first().focus();

FIDDLE

Don't use the attributes selector with ID's, just using the ID selector is much faster.
You can use the :input selector, it selects all input elements, like input, textarea, select and button.
Then use either :first or first() to get the first one.

EDIT: based on the comment, the ID is not constant, so using the tagName and :eq() you can select the second form, and as :eq() is zero based, the second one would be 1

Upvotes: 4

Remco van Dalen
Remco van Dalen

Reputation: 304

The :input selector finds any valid form input element, which incluses dropdown lists and checkboxes, according to its documentation at http://api.jquery.com/input-selector/. Since it looks like it also includes hidden fields, I've also added the :visible selector to excluse hidden form elements.

<script>
    $("form[id=form2]").find(":input:visible:first").focus();
</script>

Upvotes: 3

Related Questions