jQuery Dynamically focus on the first INPUT or Tex

2019-03-11 21:15发布

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?

9条回答
Animai°情兽
2楼-- · 2019-03-11 21:26
$(":input:first").focus(); 

The :input selector grabs all input, textarea, select and button elements.

查看更多
戒情不戒烟
3楼-- · 2019-03-11 21:27

It's working for me in the load event.

$('#Div').find('input:first').focus();
查看更多
Juvenile、少年°
4楼-- · 2019-03-11 21:36

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();
}
查看更多
啃猪蹄的小仙女
5楼-- · 2019-03-11 21:36

Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").

Use instead:

$('form').filter(':input:first').focus();

or:

$('input').first().focus(); //as shown in the "correct" answer.

Also bear in mind when using .focus()

Attempting to set focus to a hidden element causes an error in Internet Explorer. Take care to only use .focus() on elements that are visible. To run an element's focus event handlers without setting focus to the element, use .triggerHandler( "focus" ) instead of .focus().

查看更多
贼婆χ
6楼-- · 2019-03-11 21:37

Here is my solution. The code should be easy enough to follow but here is the idea:

  • get all inputs, selects, and textareas
  • filter out all buttons and hidden fields
  • filter to only enabled, visible fields
  • select the first one
  • focus the selected field

The code:

function focusFirst(parent) {
    $(parent).find('input, textarea, select')
        .not('input[type=hidden],input[type=button],input[type=submit],input[type=reset],input[type=image],button')
        .filter(':enabled:visible:first')
        .focus();
}

Then simply call focusFirst with your parent element or selector.

Selector:

focusFirst('#parentId');

Element:

var el = $('#parentId');
focusFirst(el);
查看更多
一夜七次
7楼-- · 2019-03-11 21:38

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

查看更多
登录 后发表回答