0
I’m trying to do a function that takes the values of all <div class="preco-produto">
make the total sum and population in the <div id="final">
.
I made the function that separates the number value from the String of div
, but I’m not managing to make the presentation of the total dynamic.
I need that whenever the value of each field <div class="preco-produto">
is changed, directly from the <div id="final">
also be, making an automatic calculation.
Remembering that whenever the user clicks on the "Add" button, another is created div
with the same fields of the first, ie there may be several <div class="preco-produto">
. Can someone shed some light on how I can change my code to make it happen ?
index php.:
<div id="allProducts">
<div class="produtos-wrap"> <!---- DIV A SER CLONADA / ADICIONADA !---->
<div class=" text-center select_height">
<b>Número:</b>
<div class="index" class="font-pop">1</div>
</div>
<div class="text-center select_height">
<b>ID:</b>
<div class="font-pop number_id_produto">0</div>
</div>
<div class=" select_height">
<b>Selecione um produto:</b>
<select class="selectpicker form-control teste" data-show-subtext="false"
data-live-search="true" name="select_produtos[]" onchange="initProdutos(this)">
<?php
foreach ($result2 as $item_produtos) {
echo '<option data-subtext="' . $item_produtos['desc_produto'] . '" value="'
. $item_produtos['desc_produto'] . '">' . $item_produtos['desc_produto'] . '</option>';
}
?>
</select>
</div>
<div class="text-center select_height">
<b>Embalagem:</b>
<br>
<input type="text" maxlength="2" class="edit-input font-pop" name="embalagem[]" value="">
</div>
<div class="text-center select_height">
<b>Preço:</b>
<br>
<input type="text" maxlength="5" name="preco[]" class="edit-input font-pop" value="0">
</div>
<div class="text-center select_height">
<b>Quantidade:</b>
<br>
<input type="text" maxlength="3" class="edit-input font-pop" value="0"
name="quantidade-produto[]">
</div>
<div class="text-center select_height">
<b>Preço do Produto:</b>
<div class="font-pop preco-produto" onchange="split()">R$ 0</div>
</div>
<div class="text-center select_height">
<button class="remover">X</button>
</div>
</div>
</div>
<button id="add-button" onclick="">+</button>
</div>
<div class="container" id="produto-total">
<div class="assinatura col-lg-6">
Assinatura
</div>
<div class="preco-final col-lg-6">
<b>Preço total:</b>
<div id="total"></div>
</div>
</div>
Jquery:
function initProdutos(e) {
var wraper = $(e).closest(".produtos-wrap"); // pega a div principal
var letras_produtos = $(e).val()
const $preco = $("[name='preco[]']", wraper);
const $qtd = $("[name='quantidade-produto[]']", wraper);
const $total = $(".preco-produto", wraper);
const $final = $('#total');
function recalculate() {
const total = Number($preco.val() || 0) * Number($qtd.val() || 0);
$total.text("R$ " + total);
}
function sub(){
$($preco).on('change',function () {
var sub = $(this).val().replace(',', '.');
$(this).val(sub);
})
}
function split(){
$($total).each(function () {
var str = $(this).html();
var res = str.split(" ");
$($final).text(res[1]);
})
}
function total(){
$('.preco-produto div').on('change',function () {
var t = 0;
$('.preco-produto').each(function (i,e) {
if ($(e).val()){
if (isNaN(i)) {$(e).val(''); return; }
t += parseFloat(i);
$($final).text('R$ ' + t.toFixed(2));
}
})
})
}
$.ajax({
type: "GET",
url: "API.php",
data: {
"mode": "produtos", letras_produtos
},
dataType: "JSON",
//CASO DÊ TUDO CERTO
success: function (data) {
$('[name="embalagem[]"]', wraper).val(data[0]['embalagem']);
$('.number_id_produto', wraper).text(data[0]['id_produto']);
recalculate();
sub();
total();
},
error: function (request, error) {
console.log(error);
}
});
$preco.on('input', recalculate, sub());
$qtd.on('input', recalculate);
$total.on('div',split(),total());
$final.on('div',split(),total());
recalculate();
sub();
split();
total();
};
Sam, he’s making an error in the '.toLocaleString' function, did I put his code in the wrong place or something ? On the console it looks like this: https://prnt.sc/o1wroo , https://prnt.sc/o1wrxa
– Leo
Would it be better if I changed the 'price-product' element from DIV to an input ? Or you won’t have any future problems ?
– Leo
The function of formatting the coin has to have a value. Note that you only put formatMoeda() without a value.
– Sam
Leave as div has no problem at all, it is even better because it is only an illustrative element to show the value.
– Sam
I was able to fix this question, now it occurs that, whenever I remove some DIV that was with its value added in the "Total", this value is not subtracted from the Total value. How can I ask this question ?
– Leo
I changed the answer. Just call the function
calculos()
at the end of the function that removes an item from the list.– Sam
It worked out, thank you very much Sam. You would have an indication of some material or something of a kind for me to delve into the study in Jquery / Javascript ?
– Leo
W3 Schools is a good place to start.
– Sam
Okay, thank you so much for the tip and for the help Sam, thank you from my heart !
– Leo
Sam, I’m sorry to bother you, but I’d like to ask you a question about a bug that’s occurring with this code. If the value of the product by a decimal value, in the Total it does not read, and if the quantity of the product is greater than 100, the Total also Buga. What may be happening Print’s: https://prnt.sc/o2wbuf , https://prnt.sc/o2wc2n
– Leo
Just correcting, if the price of the Product passes the value of R$999, the Total price already Uga.
– Leo
Oops! Blz? Replace this line:
var p = parseFloat($(this).text().match(/[\d|,|\.]+/)[0].replace(".", "").replace(",", "."));
– Sam
It worked, thank you Sam !
– Leo