0

So i have this code that I'm trying to get it to add up all the sums plus there quantities. How it works now it only adds one of the items. What am i missing?

function addSubTotal() {
var subTotal = 0;
var total = 0;

    $("#items").find("#itemadd").each(function() {
        var qty = parseInt($(this).find("#qty").val());
        var rate = parseInt($(this).find("#price").html());
        subTotal += qty * rate; 
    });
        $("#subTotal").html(subTotal);
  }

and this is the code i use to dynamically add it

function addItem(a, b) {
$("#items").append("<div id=itemadd> <span id=remove>remove</span> <span id=item>" + a + "</span> <input id=qty type=number autocomplete=off value=2> <span id=price>" + b + "</span></div>");
addSubTotal();
}
3
  • 4
    IDs must be unique. Commented Apr 13, 2015 at 3:27
  • use a class instead of ID for repeated elements. Commented Apr 13, 2015 at 3:28
  • 1
    OMG it was that simple... Thought i was losing my mind... damn IDs... Thank you! Commented Apr 13, 2015 at 3:30

1 Answer 1

2

The problem is you are using the id attribute. An id must be unique. Otherwise, the browser will only return the first instance of an element with that id that it finds.

You want to make these classes instead, then search for .itemadd.

Check out this quick example: https://jsfiddle.net/2b7zfjha/

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

1 Comment

OMG it was that simple... Thought i was losing my mind... damn IDs... Thank you!

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.