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
<table width="100%">
<tr>
<td>
<label>
<input type="checkbox" name="colorCheckbox" id="n1" value="200" data-> Show Price
</label>
</td>
<td>
<div class="n1 box">200</div>
</td>
</tr>
<tr>
<td>
<label>
<input type="checkbox" name="colorCheckbox" id="n2" value="200" data-> Show Price
</label>
</td>
<td>
<div class="n2 box">200</div>
</td>
</tr>
<tr>
<td>
<label>
<input type="checkbox" name="colorCheckbox" id="n3" value="200" data-> Show Price
</label>
</td>
<td>
<div class="n3 box">200</div>
</td>
</tr>
<tr>
<td>
<label>
<select id="n4" data->
<option value="0" selected>Choose...</option>
<option value="10">item 1</option>
<option value="20">item 2</option>
</select>
</label>
</td>
<td>
<div class="n4"></div>
</td>
</tr>
<tr>
<td>
<label>
<select id="n5" data->
<option value="0" selected>Choose...</option>
<option value="3">item 1</option>
<option value="4">item 2</option>
</select>
</label>
</td>
<td>
<div class="n5"></div>
</td>
</tr>
<tr>
<td> Total: </td>
<td>
<div id="sum">0</div>
</td>
</tr>
</table>
JavaScript
$(function() {
function getTotal() {
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"