views:

53

answers:

5

Here's a tricky one to start the morning.

I have a series of icons. When you click an icon it loads a form. Some of the forms have input[text] others have textareas.

What I'm trying to come up with is jQuery that once I load the form I can run that will... Focus in on the first input or textarea whatever it may be, dynamically so I don't need if blocks.

Ideas?

+2  A: 

EDIT

This is actually not that great of a solution. Patricia's and Onkelborg's solutions below are much more elegant.

var $firstInput = jQuery("input:first");
var $firstTextArea = jQuery("textarea:first");

if(firstInput.length == 0) {
  $firstTextArea.focus();
}

else {
  $firstInput.focus();
}
Vivin Paliath
hmm not working. Could it be because I'm using AJAX to inject the form into the page?
TheExit
@user485680: No, AJAX has nothing to do with it. Have you replaced "formId" with the id of the form?
Onkelborg
+3  A: 

This should do it I think

$("#formId input:text, #formId textarea").first().focus();
Onkelborg
that did it, thank you!
TheExit
+1 This one works as well. Ignore my answer.
Vivin Paliath
@user485680: I would appreciate if you accepted this answer :)
Onkelborg
Much simpler, ignore mine.
Tom Walters
A: 

As long as you have already set up the click function to show/hide the forms, use

$("input:text:visible:first").focus();
$("textarea:visible:first").focus();

To apply focus to the first field/textarea of each form.

Tom Walters
It's either one or the other not both?
TheExit
Won't work since it's always the first textarea that's going to get focus
Onkelborg
This won't work.
Vivin Paliath
You're totally correct, sorry, use $("form > :first").first().focus();
Tom Walters
+2  A: 

some of your code would be nice.. but this should be easy.

assuming your loading your for into a div that you know the id of....

all you have to do is something like

$('#TheIdOfYourFormDiv').find('input, textarea').first().focus()

after you've loaded your form

Patricia
+1 Ignore my answer. Patricia's is right.
Vivin Paliath
This is once again the power of jQuery. `dothis.dothat.thendothis` I love it!
Justus Romijn
A: 

$(":input:first").focus();

Tom Brothers