박두준 박두준 -4 years ago 110
HTML Question

Add values using checkbox in jquery?

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>




Answer Source

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];
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download