简体   繁体   中英

Select the first element in a set of CSS selectors

On a project I'm working on, one of the conventions we want to set up for our users, is that when we open a modal, we automatically focus the first element of the opened modal that can accept an input (either an input or a dropdown.) The jQuery code for doing that is easy :

$firstElement.focus();

The problem, is getting that first element.

Our application's modals sometimes start with input s (eg text, checkboxes, dates, etc.), but other times with select s (eg dropdowns.) Thus, getting the $firstElement is a bit challenging because I need to perform a selection like the following pseudocode:

(input, select):first

However, the closest I've been able to get based on my knowledge of CSS selectors is:

input:first, select:first

Question: Using CSS selectors, in what way can I select the first element of a set of inputs and selects? Or, do I need a more complex JavaScript implementation to perform the 'focus first input' thing I'm trying to do?

Try this:

var $firstElement = $("input, select, textarea").first();

Addendum:

In case you're using hidden inputs , there's a way around that as well:

var $firstElement = $("input, select, textarea").filter(':visible:first');

You can use $.fn.first()

Reduce the set of matched elements to the first in the set.

$('input, select').first().focus();
var tabbableElements  = 'a[href], area[href], input:not([type="radio"]):not([disabled]),' +
                                'input[type="radio"]:checked:not([disabled]),' +
                                'select:not([disabled]), textarea:not([disabled]),' +
                                'button:not([disabled]), iframe, object, embed, *[tabindex],' +
                                '*[contenteditable]';
var $allTabbableElements = $(context).find(tabbableElements).filter(':visible');
var firstTabbableElement = $allTabbableElements.first()[0];

This is part of a code i use for keeping focus within a modal. Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM