0

I'm trying to set focus on the first input field in an element with class of .search-options that comes next one the page.

This is what I am using, however its not working.

$(document).ready(function() {
    $('.toggle-search-options').on('click', function() {
        $(this).next('.search-options *:input[type!=hidden]:first').focus();
    });
});
zemaker
  • 181
  • 1
  • 2
  • 15

2 Answers2

2

This is very similar to this: jQuery: Find next element that is not a sibling, except that the current element doesn't match the selector you are looking for. In that case you simply have to add it to the selection:

// Outside the event handler:
var $elements = $('.search-options *:input[type!=hidden]');

// Inside the event handler:
var $elementsWithCurrentElement = $elements.add(this);
$elementsWithCurrentElement.eq($elementsWithCurrentElement.index(this) + 1).focus();

If the element you are looking for is actually a sibling, have a look at Efficient, concise way to find next matching sibling? .

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • There must be a cleaner way of doing this with $(this).next – zemaker Jan 14 '16 at 20:20
  • Well, that's simply not what `.next` is there for: *"Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector."* https://api.jquery.com/next/ . I.e. `$(this).next(...)` returns the next sibling *if and only if* the selector matches, otherwise an empty set. `.next` and `.nextAll` only work on the *siblings* of the selected element(s), not *all* following elements. I suggest to have a look at the examples in the documentation to get a better idea of how they work. – Felix Kling Jan 14 '16 at 20:22
  • That's nice to know. Thanks for your help, I will go with it as it does what I need it to do. – zemaker Jan 14 '16 at 20:31
0

I didn't understand the need for the colon in front of "input". This worked just fine for me:

$('#test input[type!="hidden"]:first')

But as an alternate solution, why not grab the first in the array of matches?

var inputs = $('#test input[type!="hidden"]');
if(inputs.length > 0) { $(inputs[0]).focus(); }
Nate
  • 1,268
  • 13
  • 20