Sum selected items

Asked

Viewed 45 times

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(), for total += $(this).text().replace('.','').replace(',','.') does not solve your problem?

  • Had to convert to float also!

2 answers

2

Convert to float:

    function calculaTotal() {
     var total = 0;
     if ($(".iten-preco").length > 0) {
       $(".iten-preco").each(function(){
         total += parseFloat($(this).text().replace(/\./g, 
       '').replace(/,/g, '.'));
       });
     }
     $('#total-orcamento').text(total);
    }

2


You have two mistakes in function calculaTotal:

01. Taking into account that you use a comma to separate decimals, Javascript does not understand that it is a decimal number. Thus, you must make a conversion to float after replace the comma with a dot.

To perform the conversion, you can do something like this:

function toFloat(num) {
  return parseFloat(num.replace(/\./g, '').replace(/,/g, '.'))
}

console.log(toFloat('987.654,321'))

02. You are making a string concatenation when using the operator += without using numbers in both operands. However, this problem is already solved by the previous topic.

An example of the unwanted concatenation you are making:

let initialValue = 0

initialValue += '3'
initialValue += '5'

console.log(initialValue, typeof initialValue)


So:

function calculaTotal() {
  var total = 0

  if ($('.iten-preco').length > 0) {
    $('.iten-preco').each(function() {
      total += parseFloat($(this).text().replace(/\./g, '').replace(/,/g, '.'))
    })
  }
  $('#total-orcamento').text(total)
}
  • With this replace you only replace the first occurrence of the character "."

  • That’s true! Thanks for the remark. In this case, regular expressions like /\./g are more convenient... I will edit the answer! :)

  • Solved, thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.