1

I'm trying to add the values when a certain checkbox is selected, but it only adds the very first and ignores the next checkbox selected. For example, I selected Cheese and then Bacon, it only adds Cheese and Bacon's value is ignored.

  var total = 0;
  
  if ($("input:checkbox[name='extras']:checked").val() == "Cheese") {
      total += 1.50 * 1;
    } else if ($("input:checkbox[name='extras']:checked").val() == "Pepperoni") {
      total += 1.50 * 1;
    } else if ($("input:checkbox[name='extras']:checked").val() == "Mushrooms") {
      total += 1.50 * 1;
    } else if ($("input:checkbox[name='extras']:checked").val() == "Bacon") {
      total += 1.50 * 1;
    } else if ($("input:checkbox[name='extras']:checked").val() == "Olives") {
      total += 1.50 * 1;
    }
    $("#ttl").html("Total Charge: $" + total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="extras" value="Cheese">Cheese
    <br>
    <input type="checkbox" name="extras" value="Pepperoni">Pepperoni
    <br>
    <input type="checkbox" name="extras" value="Mushrooms">Mushrooms
    <br>
    <input type="checkbox" name="extras" value="Bacon">Bacon
    <br>
    <input type="checkbox" name="extras" value="Olives">Olives
    <br>
    <br><span id="ttl"></span>

1 Answer 1

4

You need to loop over all the selected checkboxes. When you call .val() on a selector that matches multiple elements, it just returns the value of the first match.

And instead of a big if/else if/... block, use a data structure to hold the prices.

var prices = {
    Cheese: 1.50,
    Pepperoni: 1.50,
    ...
};

$(":checkbox[name=extras]:checked").each(function() {
    total += prices[this.value];
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. I appreciate the help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.