Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Dynamically focus on the first INPUT or Textarea

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?

like image 523
TheExit Avatar asked Oct 26 '10 17:10

TheExit


People also ask

How to focus first element in jQuery?

Just in case you want to focus on the first element in a form, here is how to do it through one simple jQuery sector: $('#form-id :input:enabled:visible:first'). focus();

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 change the input focus on a modal?

Answer: Use the jQuery . focus() method focus() method to set the focus on the first input box or textarea inside the Bootstrap modal when it is loaded upon activation.

How do I get focus on modal pop up?

tab, shift + tab and enter key and focus should be trapped inside modal and should not go out after pressing tab key multiple times.


2 Answers

This should do it I think

$("#formId input:text, #formId textarea").first().focus(); 
like image 77
Onkelborg Avatar answered Sep 22 '22 03:09

Onkelborg


Here it is:

$('#form-id :input:enabled:visible:first').focus(); 

#form-id is ID of the form; :input selects any input and textarea element; :enabled ensures the input is editable; :viisble ensures that the element is visible; :first is obvious

like image 38
Viliam Avatar answered Sep 20 '22 03:09

Viliam