Realtime calculate
Based on codepen.io/dees040/pen/yVJEWQ
by Thomas Doe
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tr>
<th>
Omschrijving
</th>
<th>
Ex BTW
</th>
<th>
Aantal
</th>
<th>
Uitkomst
</th>
</tr>
<tr>
<td>
omschrijving 1
</td>
<td class="price">
0,9990
</td>
<td>
<input type="number" name="amount" class="amount" value="1" min="0">
</td>
<td class="output">
</td>
</tr>
<tr>
<td>
omschrijving 2
</td>
<td class="price">
2,550
</td>
<td>
<input type="number" name="amount" class="amount" value="2" min="0">
</td>
<td class="output">
</td>
</tr>
<tr>
<td>
omschrijving 3
</td>
<td class="price">
3,210
</td>
<td>
<input type="number" name="amount" class="amount" value="1" min="0">
</td>
<td class="output">
</td>
</tr>
<tr>
<td></td>
<td>
Uitkomst
</td>
<td>
EX BTW
</td>
<td >
<input type="checkbox" id="use_set_without_vat"/>
<input type="text" class="output-no-vat" id="out_novat" />
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
BTW
</td>
<td class="output-vat">
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Totaal</td>
<td class="output-total">
</td>
</tr>
</table>
JavaScript
Number.prototype.toEur = function (){
var output = (Math.floor((this*100))/100).toFixed(2).replace('.',',');
return '€ '+output;
}
String.prototype.ToInt = function (){
var output = parseFloat(this.replace('€','').replace(',','.'));
return output;
}
var app = {
initialize: function () {
app.setListeners();
if($('#use_set_without_vat:checked').length != 0){
app.costumwithoutvat();
}else{
app.calculate();
}
var costumwithoutvat_var;
},
setListeners: function () {
$('body').on('input', '.amount', app.calculate);
$('body').on('blur', '#out_novat', app.costumwithoutvat);
$('body').on('change', '#use_set_without_vat', app.recalculate);
},
recalculate: function(){
if($(this).is(":not(:checked)")){
app.calculate();
}
},
costumwithoutvat: function() {
costumwithoutvat_var = $('#out_novat').val().ToInt();
$('#use_set_without_vat').prop( "checked", true );
app.calculate();
},
calculate: function () {
var totalWithoutVat = 0;
$('.amount').each(function () {
var $parent = $(this).closest('tr');
var price = $(this).val() * $parent.find('.price').text().replace(',', '.');
totalWithoutVat += price;
$parent.find('.output').text(price.toEur());
});
if($('#use_set_without_vat:checked').length != 0){
totalWithoutVat = costumwithoutvat_var;
}
var totalVat = (totalWithoutVat / 100 * 21).toEur();
var totalWithVat = (totalWithoutVat * 1.21).toEur();
totalWithoutVat = totalWithoutVat.toEur();
$('.output-no-vat').val(totalWithoutVat);
$('.output-vat').text(totalVat);
$('.output-total').text(totalWithVat);
}
};
$(document).ready(function () {
app.initialize();
});