0
I have a select
showing products that can be inserted in a table by clicking the button + .
Previously when values were displayed in the format as in the database (
9999.99
) I could calculate the value of the selected items correctly, but when I started to present the values in Real format (9.999,99
) I could no longer calculate the total of the products selected.
I was applying a conversion in the calculation of this function:
function calculaTotal(){
var total = 0;
if ($(".iten-preco").length > 0){
$(".iten-preco").each(function(){
total += $(this).text();
});
}
$('#total-orcamento').text(total);
}
Complete code:
function loadItens(){
$.getJSON("https://api.myjson.com/bins/10hz22",function(data){
itens = data;
$.each(data, function(key, val){
$("#select-iten").append("<option value='"+key+"'>"+
val.nome+" ("+ toReal(val.preco) +")</option>");
});
});
}
loadItens();
var itens;
$("#add-iten").click(function(){
var si = $("#select-iten").val();
$(".itens").append("<tr class='iten-added'>"+
"<td>"+itens[si].id+"</td>"+
"<td>"+itens[si].nome+"</td>"+
"<td class='iten-preco'>"+ toReal(itens[si].preco) +"</td>"+
"<td><button class='iten-delete btn btn-danger'>-</button></td>"+
"</tr>");
calculaTotal();
});
$(document).on("click", ".iten-delete", function(){
$(this).parents("tr").remove();
calculaTotal();
});
function calculaTotal(){
var total = 0;
if ($(".iten-preco").length > 0){
$(".iten-preco").each(function(){
total += $(this).text();
});
}
$('#total-orcamento').text(total);
}
function toReal(str){
str = parseFloat(str).toLocaleString('pt-br',{minimumFractionDigits: 2});
return str;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<form class="form-inline">
<label for="select-iten">Produtos: </label>
<select id="select-iten" class="form-control">
<option>Selecione</option>
</select>
<input class="btn btn-primary" type="button" id="add-iten" value="+">
</form>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>#</th>
<th>Nome</th>
<th>Preço</th>
<th>Ação</th>
</tr>
</thead>
<tbody class="itens">
</tbody>
<tfoot>
<tr>
<td colspan="2">Total: </td>
<td colspan="2" id="total-orcamento"></td>
</tr>
</tfoot>
</table>
</div>
If you change
total += $(this).text()
, fortotal += $(this).text().replace('.','').replace(',','.')
does not solve your problem?– Felipe Avelar
Had to convert to
float
also!– Laércio Lopes