Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Łukasz Czuliński
8,646 PointsTrying to get value of hidden input but returning 'undefined'.
Hi eall. As said in the title, I'm trying to return the value of an input.
var itemBar = document.getElementsByClassName('quote-item-bar');
for(var i = 0; i < itemBar.length; i++){
var position = itemBar[i].getElementsByClassName('position');
console.log(i, position.value);
}
which returns
0 undefined
1 undefined
Here are the html inputs
<input class="position" name="item_position[]" type="hidden" value="2">
<input class="position" name="item_position[]" type="hidden" value="3">
Despite them having values of 2 and 3 respectively. What super-simple thing am I missing here?
2 Answers
Robert Richey
Courses Plus Student 16,352 PointsWhen getting elements by class name, you're getting an array of nodes unless you specify the index you want.
document.getElementsByClassName("position")[i];
An individual input element has a value property but an array of input elements do not.
Edited for clarity
Łukasz Czuliński
8,646 PointsI get what you mean, but I can't just get all .position elements. I need to get the ones that are only within a particular div (.quote-item-bar). There are more on the page that I want to ignore.
I'm trying to avoid doing this without adding a second class that is unique to these inputs.
Łukasz Czuliński
8,646 PointsNevermind, got it. Because I know there is only one instance of position all I did was:
var position = itemBar[i].getElementsByClassName('position')[0].value;
I suppose I could just do a second for loop within the function if the number is dynamic. Thanks for the help.