1

I have

<div id="exp">
  <input type="hidden" name="sum[]" value="1" />
  <input type="hidden" name="sum[]" value="2" />
  <input type="hidden" name="sum[]" value="3" />
  <input type="hidden" name="sum[]" value="4" />
</div>

And I want in jquery get the value of the last element of the array. I've tried:

alert(sum[sum.length-1]);

But shows me 'undefined'. What am I doing wrong?

1
  • You're assuming elements named sum[] can be accessed through a global array variable named sum. That's not the case. To obtain the last element within a container, you have to query the DOM as jfriend00 demonstrates in his answer. Commented Apr 15, 2012 at 15:45

1 Answer 1

6

You can use this:

var lastValue = $("#exp input:last").val();

This uses a jQuery selector to find the last input element that is a child of #exp and get its value.

You can see it work here: http://jsfiddle.net/jfriend00/Lh7sJ/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.