How To Calculate Totals In Jquery With Dropdowns
I am trying to get the dropdowns in the code below working like the checkboxes. The checkboxes when checked reveal a price and the revealed prices then get totaled. I also want the
Solution 1:
Consider the following.
Fiddle: https://jsfiddle.net/Twisty/hpd415fj/46/
HTML
<tablewidth="100%"><tr><td><label><inputtype="checkbox"name="colorCheckbox"id="n1"value="200"data-> Show Price
</label></td><td><divclass="n1 box">200</div></td></tr><tr><td><label><inputtype="checkbox"name="colorCheckbox"id="n2"value="200"data-> Show Price
</label></td><td><divclass="n2 box">200</div></td></tr><tr><td><label><inputtype="checkbox"name="colorCheckbox"id="n3"value="200"data-> Show Price
</label></td><td><divclass="n3 box">200</div></td></tr><tr><td><label><selectid="n4"data-><optionvalue="0"selected>Choose...</option><optionvalue="10">item 1</option><optionvalue="20">item 2</option></select></label></td><td><divclass="n4"></div></td></tr><tr><td><label><selectid="n5"data-><optionvalue="0"selected>Choose...</option><optionvalue="3">item 1</option><optionvalue="4">item 2</option></select></label></td><td><divclass="n5"></div></td></tr><tr><td> Total: </td><td><divid="sum">0</div></td></tr></table>
JavaScript
$(function() {
functiongetTotal() {
var total = 0;
$("input, select").each(function(i, el) {
if ($(el).is("input:checked")) {
$($(el).data("rel")).show();
total += parseInt($(el).val());
} else {
$($(el).data("rel")).hide();
}
if ($(el).is("select")) {
if ($(el).val() !== "0") {
$($(el).data("rel")).html($(el).val()).show();
total += parseInt($(el).val());
} else {
$($(el).data("rel")).html($(el).val()).hide();
}
}
});
return total;
}
$('input[type="checkbox"], select').change(function() {
$("#sum").text(getTotal());
});
});
This loops over each element and checks it's status. You will noticed I cleaned up your HTML so it is more easily used.
I added an ID attribute, changed the Value, and added data attributes. This allows the script to gather all the details needed. You can loop over each and if is checked or selected, you can add it into the total.
It can also hide/show the relative elements.
Post a Comment for "How To Calculate Totals In Jquery With Dropdowns"