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
Eric Ewers
13,976 PointsAdd sum of select box values with same ID using jQuery
I found a partial solution, but I need to add an id of "product" to all of these select boxes, then get the sum of only the selects with id="product". That way, if I have other select boxes in my form, they won't get targeted.
$("select").change(function() {
var combined = 0;
$("select").each(function() {
combined += parseInt(this.value);
});
$("#sum").html(combined);
}).trigger("change");
<select>
<option value=1>1</option>
<option value=15>15</option>
</select>
<select>
<option value=1>1</option>
<option value=25>25</option>
</select>
<select>
<option value=1>1</option>
<option value=2>2</option>
</select>
<p>
Sum :<span id="sum">0</span>
</p>
When I try the following, it only targets the first select, but not the rest.
$("#product").change(function() {
var combined = 0;
$("#product").each(function() {
combined += parseInt(this.value);
});
$("#sum").html(combined);
}).trigger("change");
1 Answer
Hugo Paz
15,622 PointsHi Eric,
Your issue is pretty simple, you are using IDs. IDs are supposed to be unique, only one per page if you will.
Change it from an ID to a Class and your code works perfectly.
Eric Ewers
13,976 PointsEric Ewers
13,976 PointsWow...that is what happens when you stare at the screen too long. Thanks!