Sasha Grievus
Sasha Grievus

Reputation: 2686

Hot to get the 'value' of the last element of type 'input' with a certain 'name'?

In my html page i have some fields like this, in this order:

< input type="hidden" name="foo" value="age:1">
< some other code >
< input type="hidden" name="foo" value="age:2">
< some other code >
<...>
< input type="hidden" name="foo" value="age:7">

In jquery how do I get 'age:7' that is the 'value' of the last element in page of type 'input' with a certain 'name' (without touching html!)?

I mean something like

$( "input[name='foo']" ).val()

but the last one found in page.

Upvotes: 2

Views: 72

Answers (3)

Rounin
Rounin

Reputation: 29463

For the sake of comparison, I thought I would write out the library-less Javascript equivalent:

var lastFooValue = document.querySelector('input[name="foo"]:last-of-type').value;

(It's almost identical to the jQuery...)

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you can use .last()

$( "input[name='foo']" ).last().val()

Upvotes: 3

AmmarCSE
AmmarCSE

Reputation: 30557

Use the :last selector

$( "input[name='foo']:last" ).val()

Upvotes: 4

Related Questions