jQuery Dynamically focus on the first INPUT or Textarea

后端 未结 9 1400
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-29 04:11

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

9条回答
  •  無奈伤痛
    2020-12-29 04:22

    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().

提交回复
热议问题