JSFiddle - React, Tailwind, and code Playground
by Ivan Ferrer
HTML
<h2>Itens da lista:</h2>
<div id="qtde_elementos">
<form action="" method="post">
<div>
<label>Prd 1:</label>
<input data-check="0" type="checkbox" name="active" value="true">
<input data-id="0" data-name="Prd 1" data-active="false" disabled="disabled" class="qtde" type="number" data-price="2.00" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0"> R$ 2,00
</div>
<div>
<label>Prd 2:</label>
<input data-check="1" type="checkbox" name="active" value="true">
<input data-id="1" data-name="Prd 2" data-active="false" disabled="disabled" class="qtde" type="number" data-price="4.00" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0"> R$ 4,00
</div>
<div>
<label>Prd 3:</label>
<input data-check="2" type="checkbox" name="active" value="true">
<input data-id="2" data-name="Prd 3" data-active="false" disabled="disabled" class="qtde" type="number" data-price="3.50" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0"> R$ 3,50
</div>
</form>
</div>
<div class="total" data-total>Total: <span>R$ 0,00</span>
</div>
<div id="view_json"></div>
CSS
body {
font-family: Arial;
font-size:14px;
}
#qtde_elementos input[type="number"] {
width:60px;
padding:5px;
margin:6px 0;
}
#qtde_elementos div {
display:block;
}
.total span {
font-weight: bold;
margin-left:12px;
margin-top:10px;
}
JavaScript
$('[data-id]').change(function () {
var data = {
id: $(this).data('id'),
value: $(this).val(),
price: $(this).data('price'),
name: $(this).data('name'),
active:true
}
$('body').trigger('total.update', [data]);
});
$('[data-check]').click(function () {
if ($(this).is(':checked')) {
$('[data-id="' + $(this).data('check') + '"]')
.attr('disabled', false)
.data('active', true);
} else {
var data = {
id: $(this).data('check'),
value:0,
price:0,
name: $('[data-id="' + $(this).data('check') + '"]').data('name'),
active:false
}
$('body').trigger('total.update', [data]);
$('[data-id="' + $(this).data('check') + '"]')
.attr('disabled', true)
.val('')
.data('active', false);
}
});
(function () {
var Total = function (el) {
this.allData = new Array();
this.dados = new Array();
this.$el = el;
this.value = 0;
this.price = 0;
this.products = new Array();
$('body').on('total.update', $.proxy(this, 'update'));
}
Total.prototype.update = function (e, data) {
this.products[data.id] = this.multiply(data.value, data.price);
this.value = this.products.reduce(this.reduce);
this.render.apply(this);
this.jsonModel(data, this.value);
}
Total.prototype.multiply = function (qtde, price) {
return parseInt(qtde) * parseFloat(price);
}
Total.prototype.reduce = function (prev, current) {
return parseFloat(current) + parseFloat(prev);
}
Total.prototype.render = function () {
this.$el.find('span').html(currencyFormatted(parseFloat(this.value), 'R$'));
}
Total.prototype.jsonModel = function(data, total) {
if...