Help in subtraction calculation with jquery

Asked

Viewed 115 times

0

I have the following field:

inserir a descrição da imagem aqui

The goal is as it is including the adult, it adds up the values and when remove field, it subtracts. Taking into account that the package is 150.00 and each adult is 50.00, the addition calculation is working correctly. The problem is in the subtraction. When I try to remove an adult, the calculation is not coming out the right way. I am doing it this way:

<input type="hidden" name="SubTotal" id="subTotalForm" value="">
  <input type="hidden" name="ValorTotal" id="totalForm" value="">
    <table border="0" width="100%">
      <tr class='linhas'>
        <td>
        <table border="0" width="100%">
          <tr>
            <td  style="padding: 5px">
              <select name="TipoPassageiro[]" class="form-control TipoPassageiro">
                <option value="">Tipo de Passageiro</option>
                <option data-tipo="1" value="Adulto">Adulto</option>
                <option data-tipo="2" value="Crianca6Anos">Criança de colo de até 6 anos</option>
                <option data-tipo="3" value="Crianca6a12Anos">Criança entre 6 e 12 anos</option>
                <option data-tipo="4" value="Adolescentes">Adolescente entre 12 e 18 anos</option>
              </select>
            </td>
          <td  style="padding: 5px"><input type="text" name="NomePAX[]" class="form-control" placeholder="Nome do pax" value=""></td>
          <td  style="padding: 5px">
            <select id="TipoDocumento" name="TipoDocumento[]" class="form-control">
              <option>Tipo de documento</option>
              <option value="Carteira de Identidade">Carteira de Identidade</option>
              <option value="Carteira Nacional de Habilitação">Carteira Nacional de Habilitação</option>
              <option value="Carteira de Trabalho">Carteira de Trabalho</option>
              <option value="Certidão de Nascimento">Certidão de Nascimento</option>
              <option value="Passaporte">Passaporte</option>
              <option value="Cédula de Identidade Estrangeira">Cédula de Identidade Estrangeira</option>
              <option value="Outros">Outros</option>
            </select>
          </td>
          <td  style="padding: 5px">
             <input type="text" name="Documento[]" class="form-control" placeholder="RG da pessoa autorizada" value="">
          </td>
          <td  style="padding: 5px">
             <input type="text" name="OrgaoEmissor[]" class="form-control" placeholder="Órgão Emissor" value="">
          </td>
        </tr>
      </table>
      </td>
          <td style="padding: 5px" valign="top"><button type="button" class="removerCampo btn btn-danger" title="Remover linha"><i class="fa fa-minus-square" aria-hidden="true"></i> Remover</button></td>
      <tr>
          <td colspan="3"><button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"><i class="fa fa-plus-square" aria-hidden="true"></i> Adicionar mais passageiros</button></td>
      </tr>
      </table>
    <div class="text-right">
      <strong>Valor do Pacote:</strong> <span style="font-family: Arial"> R$ 150,00</span><br>
      <strong>Valor Subtotal:</strong>
      <span style="font-family: Arial">
         R$ <span id="valorsubtotal">0,00</span>
      </span>
      <br>
      <strong>Valor Total:</strong>
      <span style="font-family: Arial">
         R$ <span id="valortotal">150,00</span>
      </span>
    </div>
  </div>
    <div class="form-group text-center" style="margin-top: 10px">
      <button type="submit" class="btn btn-primary">FINALIZAR <i class="fas fa-angle-double-right"></i></button>
    </div>

and Jquery

     $(function () {
       function removeCampo() {
             $(".removerCampo").unbind("click");
             $(".removerCampo").bind("click", function () {
                if($("tr.linhas").length > 1){
                   var campo = $(".TipoPassageiro:last").val();
                   //var valor_subtotal = 0;
                   var valor_subtotal = $("#subTotalForm").val();
                   var valor_total = $("#valortotal").val();

                   if(campo == 'Adulto'){
                    valor = <?php echo $visualizar[1]->ValorAdulto; ?>.toFixed(2).replace(" ",".");
                    var valorSubTotal = valor_subtotal - valor;
                    document.getElementById("subTotalForm").value = valorSubTotal.toFixed(2).replace(" ",".");
                    $("#valorsubtotal").text(valorSubTotal.toFixed(2).replace(".", ","));
                    if(valor_total == 150.00){
                       var valor_total = 150.00;
                       var valor_total = valor_total.toFixed(2).replace(" ",".");
                       var valorTotal = valor_total - valor;
                    }else{
                      var valor_total = $("#valortotal").val();
                      var valor_total = valor_total.toFixed(2).replace(" ",".");
                      var valorTotal = valor_total - valor;
                    }
                    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
                  }
                    $(this).parent().parent().remove();
                 }
             });
       }
       $(".adicionarCampo").click(function () {
          novoCampo = $("tr.linhas:first").clone();
          novoCampo.find('input[type="text"]').val("");
          novoCampo.find('select').val("");
          novoCampo.insertAfter("tr.linhas:last");
          removeCampo();
});
$(document).on("change", ".TipoPassageiro", function(){
   // objeto com os preços separados por "tipo"
    var precos = {
       tipo1: <?php echo $visualizar[1]->ValorAdulto; ?>,
       tipo2: <?php echo $visualizar[1]->ValorCrianca6Anos; ?>,
       tipo3: <?php echo $visualizar[1]->ValorCrianca6a12Anos; ?>,
       tipo4: <?php echo $visualizar[1]->ValorAdolescentes; ?>
    }
    // inicia o valor total com 0
    var valor_subtotal = 0;
    var valor_total = 150.00;
    // laço que irá percorrer os selects e somar de acordo com o tipo selecionado
    $(".TipoPassageiro").each(function(){
       // pega o valor do tipo (1, 2, 3 ou 4)
       var tipo = $("option:selected", this).data("tipo");
       // só inclui na soma o select que tiver um tipo selecionado
       if(tipo) valor_subtotal += parseFloat(precos['tipo'+tipo]);
    });
    // formata a soma final com duas casas decimais separadas por vírgula
    $("#valorsubtotal").text(valor_subtotal.toFixed(2).replace(".", ","));
    var valorTotal = valor_subtotal + valor_total;
    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
    document.getElementById("subTotalForm").value = valor_subtotal.toFixed(2).replace(" ",".");
    document.getElementById("totalForm").value = valorTotal.toFixed(2).replace(" ",".");
  });
});

1 answer

2


The code has several problems. At various points you redeclare the variables, for example:

var valor_total = 150.00;
var valor_total = valor_total.toFixed(2).replace(" ",".");
var valorTotal = valor_total - valor;

If you had already declared the variable with var before, do not put again the var:

var valor_total = $("#valortotal").val(); // AQUI A VARIÁVEL FOI DECLARADA
...
valor_total = 150.00; // AQUI VOCÊ APENAS ALTERA O SEU VALOR (SEM var)
valor_total = valor_total.toFixed(2).replace(" ","."); // E AQUI TAMBÉM
var valorTotal = valor_total - valor;

On this line, the dial is wrong:

var campo = $(".TipoPassageiro:last").val();

Always fetch the last select, which does not match the button you clicked on. The correct one would be:

var campo = $(this).closest("tr").find(".TipoPassageiro").val();

You will find the select that is on the same line as the button you clicked.

And here you find no value because #valortotal is a div:

var valor_total = $("#valortotal").val();

The correct would be to take the text and convert to number with parseFloat() (without the var, as said before):

valor_total = parseFloat($("#valortotal").text());

It’ll stay that way:

$(function () {
       function removeCampo() {
             $(".removerCampo").unbind("click");
             $(".removerCampo").bind("click", function () {
                if($("tr.linhas").length > 1){
                   var campo = $(this).closest("tr").find(".TipoPassageiro").val();
                   //var valor_subtotal = 0;
                   var valor_subtotal = $("#subTotalForm").val();
                   var valor_total = $("#valortotal").val();

                   if(campo == 'Adulto'){
                    valor = <?php echo $visualizar[1]->ValorAdulto; ?>.toFixed(2).replace(" ",".");
                    var valorSubTotal = valor_subtotal - valor;
                    document.getElementById("subTotalForm").value = valorSubTotal.toFixed(2).replace(" ",".");
                    $("#valorsubtotal").text(valorSubTotal.toFixed(2).replace(".", ","));
                    if(valor_total == 150.00){
                     valor_total = 150.00;
                     valor_total = valor_total.toFixed(2).replace(" ",".");
                    }else{
                      valor_total = parseFloat($("#valortotal").text());
                      valor_total = valor_total.toFixed(2).replace(" ",".");
                    }
                    var valorTotal = valor_total - valor;
                    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
                  }
                    $(this).parent().parent().remove();
                 }
             });
       }
       $(".adicionarCampo").click(function () {
          novoCampo = $("tr.linhas:first").clone();
          novoCampo.find('input[type="text"]').val("");
          novoCampo.find('select').val("");
          novoCampo.insertAfter("tr.linhas:last");
          removeCampo();
});
$(document).on("change", ".TipoPassageiro", function(){
   // objeto com os preços separados por "tipo"
   var precos = {
       tipo1: <?php echo $visualizar[1]->ValorAdulto; ?>,
       tipo2: <?php echo $visualizar[1]->ValorCrianca6Anos; ?>,
       tipo3: <?php echo $visualizar[1]->ValorCrianca6a12Anos; ?>,
       tipo4: <?php echo $visualizar[1]->ValorAdolescentes; ?>
    }    
    // inicia o valor total com 0
    var valor_subtotal = 0;
    var valor_total = 150.00;
    // laço que irá percorrer os selects e somar de acordo com o tipo selecionado
    $(".TipoPassageiro").each(function(){
       // pega o valor do tipo (1, 2, 3 ou 4)
       var tipo = $("option:selected", this).data("tipo");
       // só inclui na soma o select que tiver um tipo selecionado
       if(tipo) valor_subtotal += parseFloat(precos['tipo'+tipo]);
    });
    // formata a soma final com duas casas decimais separadas por vírgula
    $("#valorsubtotal").text(valor_subtotal.toFixed(2).replace(".", ","));
    valorTotal = valor_subtotal + valor_total;
    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
    document.getElementById("subTotalForm").value = valor_subtotal.toFixed(2).replace(" ",".");
    document.getElementById("totalForm").value = valorTotal.toFixed(2).replace(" ",".");
  });
});

Example of working without PHP codes:

$(function () {
       function removeCampo() {
             $(".removerCampo").unbind("click");
             $(".removerCampo").bind("click", function () {
                if($("tr.linhas").length > 1){
                   var campo = $(this).closest("tr").find(".TipoPassageiro").val();
                   //var valor_subtotal = 0;
                   var valor_subtotal = $("#subTotalForm").val();
                   var valor_total = $("#valortotal").val();

                   if(campo == 'Adulto'){
                    valor = (50).toFixed(2).replace(" ",".");
                    var valorSubTotal = valor_subtotal - valor;
                    document.getElementById("subTotalForm").value = valorSubTotal.toFixed(2).replace(" ",".");
                    $("#valorsubtotal").text(valorSubTotal.toFixed(2).replace(".", ","));
                    if(valor_total == 150.00){
                     valor_total = 150.00;
                     valor_total = valor_total.toFixed(2).replace(" ",".");
                    }else{
                      valor_total = parseFloat($("#valortotal").text());
                      valor_total = valor_total.toFixed(2).replace(" ",".");
                    }
                    var valorTotal = valor_total - valor;
                    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
                  }
                    $(this).parent().parent().remove();
                 }
             });
       }
       $(".adicionarCampo").click(function () {
          novoCampo = $("tr.linhas:first").clone();
          novoCampo.find('input[type="text"]').val("");
          novoCampo.find('select').val("");
          novoCampo.insertAfter("tr.linhas:last");
          removeCampo();
});
$(document).on("change", ".TipoPassageiro", function(){
   // objeto com os preços separados por "tipo"
   var precos = {
       tipo1: 50,
       tipo2: 20,
       tipo3: 10,
       tipo4: 30
    }
    
    // inicia o valor total com 0
    var valor_subtotal = 0;
    var valor_total = 150.00;
    // laço que irá percorrer os selects e somar de acordo com o tipo selecionado
    $(".TipoPassageiro").each(function(){
       // pega o valor do tipo (1, 2, 3 ou 4)
       var tipo = $("option:selected", this).data("tipo");
       // só inclui na soma o select que tiver um tipo selecionado
       if(tipo) valor_subtotal += parseFloat(precos['tipo'+tipo]);
    });
    // formata a soma final com duas casas decimais separadas por vírgula
    $("#valorsubtotal").text(valor_subtotal.toFixed(2).replace(".", ","));
    valorTotal = valor_subtotal + valor_total;
    $("#valortotal").text(valorTotal.toFixed(2).replace(".", ","));
    document.getElementById("subTotalForm").value = valor_subtotal.toFixed(2).replace(" ",".");
    document.getElementById("totalForm").value = valorTotal.toFixed(2).replace(" ",".");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" name="SubTotal" id="subTotalForm" value="">
  <input type="hidden" name="ValorTotal" id="totalForm" value="">
    <table border="0" width="100%">
      <tr class='linhas'>
        <td>
        <table border="0" width="100%">
          <tr>
            <td  style="padding: 5px">
              <select name="TipoPassageiro[]" class="form-control TipoPassageiro">
                <option value="">Tipo de Passageiro</option>
                <option data-tipo="1" value="Adulto">Adulto</option>
                <option data-tipo="2" value="Crianca6Anos">Criança de colo de até 6 anos</option>
                <option data-tipo="3" value="Crianca6a12Anos">Criança entre 6 e 12 anos</option>
                <option data-tipo="4" value="Adolescentes">Adolescente entre 12 e 18 anos</option>
              </select>
            </td>
          <td  style="padding: 5px"><input type="text" name="NomePAX[]" class="form-control" placeholder="Nome do pax" value=""></td>
          <td  style="padding: 5px">
            <select id="TipoDocumento" name="TipoDocumento[]" class="form-control">
              <option>Tipo de documento</option>
              <option value="Carteira de Identidade">Carteira de Identidade</option>
              <option value="Carteira Nacional de Habilitação">Carteira Nacional de Habilitação</option>
              <option value="Carteira de Trabalho">Carteira de Trabalho</option>
              <option value="Certidão de Nascimento">Certidão de Nascimento</option>
              <option value="Passaporte">Passaporte</option>
              <option value="Cédula de Identidade Estrangeira">Cédula de Identidade Estrangeira</option>
              <option value="Outros">Outros</option>
            </select>
          </td>
          <td  style="padding: 5px">
             <input type="text" name="Documento[]" class="form-control" placeholder="RG da pessoa autorizada" value="">
          </td>
          <td  style="padding: 5px">
             <input type="text" name="OrgaoEmissor[]" class="form-control" placeholder="Órgão Emissor" value="">
          </td>
        </tr>
      </table>
      </td>
          <td style="padding: 5px" valign="top"><button type="button" class="removerCampo btn btn-danger" title="Remover linha"><i class="fa fa-minus-square" aria-hidden="true"></i> Remover</button></td>
      <tr>
          <td colspan="3"><button type="button" class="adicionarCampo btn btn-primary" title="Adicionar item"><i class="fa fa-plus-square" aria-hidden="true"></i> Adicionar mais passageiros</button></td>
      </tr>
      </table>
    <div class="text-right">
      <strong>Valor do Pacote:</strong> <span style="font-family: Arial"> R$ 150,00</span><br>
      <strong>Valor Subtotal:</strong>
      <span style="font-family: Arial">
         R$ <span id="valorsubtotal">0,00</span>
      </span>
      <br>
      <strong>Valor Total:</strong>
      <span style="font-family: Arial">
         R$ <span id="valortotal">150,00</span>
      </span>
    </div>
  </div>
    <div class="form-group text-center" style="margin-top: 10px">
      <button type="submit" class="btn btn-primary">FINALIZAR <i class="fas fa-angle-double-right"></i></button>
    </div>

Editing

Add a value="" in the first select option:

<option value="">Tipo de documento</option>
  • Ball Show Sam. Thanks again for the strength!

  • 1

    @Fox.11 I added a detail at the end of the answer. Abs!

  • Okay. Thank you.

Browser other questions tagged

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