$('#button').click(function() {
alert($('.column').val());
});
How could I get the first, second, or third element in .column
?
To access element with nth index from an HTML page, use the jQuery eq() method. It is used to access the index of an element in jQuery. The eq() method refers the position of the element.
jQuery :nth-child() Selector The :nth-child(n) selector selects all elements that are the nth child, regardless of type, of their parent. Tip: Use the :nth-of-type() selector to select all elements that are the nth child, of a particular type, of their parent.
jQuery eq() Method The eq() method returns an element with a specific index number of the selected elements. The index numbers start at 0, so the first element will have the index number 0 (not 1).
myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).
$('#button').click(function() {
alert($('.column').eq(0).val()); // first element
alert($('.column').eq(1).val()); // second
alert($('.column').eq(2).val()); // third
});
I like selector strings, so I usually do this:
$('.column:eq(3)') // Fourth .column element
Use the Slice() function: http://api.jquery.com/slice/
See question: How to select a range of elements in jQuery
$('.column').slice(0, 2).each(function() {
$(this).val(); /* my value */
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With