views:

41

answers:

2

I have a several forms, and I'd like to select only the first and second input box of each form

$("form input:nth-child(1), form input:nth-child(2)");

But this doesn't work because each input has a label next to it, so there is no input that is nth-child(1).

Example at jsbin

+1  A: 

You can use eq():

$("form input:eq(0), form input:eq(1)");

This selects the first and second of the matched elements.

Felix Kling
At first I thought there was something wrong with `eq`, but then I discovered that it's zero-based... thanks, though (:
peirix
@peirix: Yes, if you are acting on the array of *matched* elements, the index is zero based. If you deal with functions that act on the DOM nodes, it is normally one-based.
Felix Kling
This is because `:eq` is a non-standard jQuery selector based on the jQuery `eq()` method, which is 0-based. The same is true of `lt`. `nth-child` is a native CSS selector; the CSS standard has taken the very regrettable policy of all indexes being 1-based.
bobince
+4  A: 

You can do it using :lt(), like this:

$("form input:lt(2)");

This selects all elements that match at less-than the passed index, the first and second elements are index 0 and 1, and will match this selector :)

Nick Craver
wohoo! one selector instead of two! sweeet (:
peirix