Viktor Horst - 3 years ago 188
HTML Question

# Calculate subtotal and total with javascript

I am trying to add two values together. The value of #price and the value of #subtotal. Subtotal is being calculated with the Jquery script and is working. The other script isn't working but does work on its own.

The div's #price, #subtotal and #total must be div's and cannot be changed into text fields with value.

Code:

``````/* JQUERY */
jQuery(document).ready(function(\$) {
\$("#checkboxdiv input:checkbox").change(function() {
var total = 0;
\$('#checkboxdiv input:checkbox:checked').each(function() {
total += parseInt(this.value, 10);
});
\$('#subtotal').text(total);
});
});

/* JAVASCRIPT */
\$(document).ready(function() {
\$("#total").append(addnumbers(\$("#price").html(), \$("#subtotal").html()));
});

function addnumbers(price, subtotal) {
return (Number(price) + Number(subtotal));
};``````

``````<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="price">10500</div>

<div id="checkboxdiv">
<input type="checkbox" value="300">Optie 1
<input type="checkbox" value="750">Optie 2
<input type="checkbox" value="25">Optie 3
<input type="checkbox" value="1200">Optie 4
</div>

<div id="subtotal"></div>

<div id="total"></div>``````

Answer Source

I'm not completely sure if I understand what you want... I guess is that when you click a checkbox, subtotal and total are updated. If that's the case, you can do it with....

``````\$("#checkboxdiv input:checkbox").change(function() {

var subtotal = 0;

\$('#checkboxdiv input:checkbox:checked').each(function() {
subtotal += parseInt(this.value, 10);
});

\$('div#subtotal').text(subtotal);
\$('div#total').text(parseInt(\$('div#price').text()) + subtotal);
});

// If you want to show the initial values, just trigger the event.
\$("#checkboxdiv input:checkbox").trigger('change');
``````

I hope it helps

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download