Recalculate when changing date or clicking the radio button

Asked

Viewed 69 times

0

Hello, How to Recalculate Values FEES AND SERVICES and the SUM OF FEES AND SERVICES when making the field change dataFim or if it is clicked on radio button = situacao_chegada.

I thank you all.

$(document).ready(function() {

  var data = new Date();
  var dia = ("0" + data.getDate()).slice(-2);
  var mes = ("0" + (data.getMonth() + 1)).slice(-2);
  var ano4 = data.getFullYear();
  var hora = ("0" + data.getHours()).slice(-2);
  var min = ("0" + data.getMinutes()).slice(-2);
  var str_data = dia + '/' + mes + '/' + ano4;
  var str_hora = hora + ':' + min;




  $("input[name=situacao]").on('change', function() {

    if ($(this).val() == "S") {
      $("#data_ini").attr("readonly", true);
      $("#data_ini").attr("disabled", true);

      $('#tab-kmUsado').hide();

    } else if ($(this).val() == "C") {
      $("#data_fim").attr("readonly", true);
      $("#data_fim").attr("disabled", true);
      $("#situacao_saida").attr("disabled", false);
      $("#data_fim").val(str_data + " " + str_hora);
      $("#tab_cliente").mouseover();
      $('#tab-avisoKmUsado').hide();
      $('#tab-kmUsado').show();


      if ($("#selectPlano").val() == "KL") {
        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_dia_kmlivre").val());
        planoTotal = $("#dias").val() * $("#valor_dia_kmlivre").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("#selectPlano").val() == "KMC") {
        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_diaria_controlada").val());
        planoTotal = $("#dias").val() * $("#valor_diaria_controlada").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("#selectPlano").val() == "DI") {
        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_diaria").val());
        planoTotal = $("#dias").val() * $("#valor_diaria").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("input[type=radio][name='seguroCarro']:checked").val() == "S") {
        $("#SegCarroS2").html($("#dias").val());
        $("#SegCarroS3").html($("#val_seguro_carro").val());
        seguroV = $("#dias").val() * $("#val_seguro_carro").val();
        $("#SegCarroS4").html(seguroV.toFixed(2));
        $(".SegCarroS4").val(seguroV.toFixed(2));
      } else {
        $("#SegCarroS2").html("0");
        $("#SegCarroS3").html("0");
        $("#SegCarroS4").html("0.00");
        $(".SegCarroS4").val("0.00");
      }

      if ($("input[type=radio][name='seguroTerceiros']:checked").val() == "S") {
        $("#SegTerceirosT2").html($("#dias").val());
        $("#SegTerceirosT3").html($("#val_seguro_terceiros").val());
        seguroT = $("#dias").val() * $("#val_seguro_terceiros").val();
        $("#SegTerceirosT4").html(seguroT.toFixed(2));
        $(".SegTerceirosT4").val(seguroT.toFixed(2));
      } else {
        $("#SegTerceirosT2").html("0");
        $("#SegTerceirosT3").html("0");
        $("#SegTerceirosT4").html("0.00");
        $(".SegTerceirosT4").val("0.00");
      }


      $(".recalcula").click();

    } else {

    }
  }).parent().find("input[name=situacao]:checked").change();





  $("#tab_cliente").on('mouseover', function() {
    DAY = 1000 * 60 * 60 * 24;

    var data_ini = $("#data_ini").val().toString().split('/');
    data_ini2 = data_ini[1] + "/" + data_ini[0] + "/" + data_ini[2];
    d1 = new Date(data_ini2);

    var data_fim = $("#data_fim").val().toString().split('/');
    data_fim2 = data_fim[1] + "/" + data_fim[0] + "/" + data_fim[2];
    d2 = new Date(data_fim2);

    $("#data_ini2").val($("#data_ini").val());

    var diasLocacao = Math.round((d2.getTime() - d1.getTime()) / DAY);

    $("#dias").val(diasLocacao);


  }).mouseover();





  $(".c").on('change', function() {

    var values = $(this).val().split('|');
    if ($(this).prop('checked')) {

      var quantity = $("table[id^=tabelaIE]").length;

      $(this).data('qty', quantity);

      var table = $("#tabelaIE").clone(true)
        .attr('id', function() {
          return this.id + quantity;
        })
        .find(':text,:file')
        .attr('id', function() {
          return this.id + quantity;
        })
        .val("")
        .end();

      //VALUE -> 1|Taxa de locação|ENC|15.00|FIX|POR|VLT|%
      //$ID_ImpEnc|$nome|$tipo|$valor|$calculo|$valor_em|$aplicacao|$a

      //APLICAÇÃO: [SEG] Sobre seguro, [KML] KmLivre, [DIA] Diária, [IE] Impostos/Encargos, [VLT] no valor total
      //VALOR EM.: [MOT] Montante, [POR] Porcentagem.
      //CALCULO..: [DIA]Por dia, [FIX]Fixo
      //TIPO.....: [TXV]Taxa de Venda, [ENC]Encargos Extras

      aplicacao = values[6];
      valor_em = values[5];
      calculo = values[4];
      tipo = values[2];

      if (valor_em == "MON" && calculo == "FIX") {
        table.find('.tNome').text(values[1]);
        table.find('.tDias').text("1");
        table.find('.tValor').text(values[3]);
        tTotal = values[3] * 1;
        table.find('.tTotal').text(tTotal.toFixed(2));
      }

      if (valor_em == "MON" && calculo == "DIA") {
        table.find('.tNome').text(values[1]);
        table.find('.tDias').text($("#dias").val());
        table.find('.tValor').text(values[3]);
        tTotal = values[3] * $("#dias").val();
        table.find('.tTotal').text(tTotal.toFixed(2));
      }

      if (valor_em == "POR" && calculo == "FIX") {
        if (aplicacao == "SEG") {
          $V = (50 + 30) / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3]);
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "KML") {
          $V = values[3] / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3]);
          tTotal = values[3] - $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "DIA") {
          $V = (values[3] * $("#dias").val()) / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text($("#dias").val());
          table.find('.tValor').text(values[3]);
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "VLT") {
          $V = $("#totalFatura").val() / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3].substring(0, 2) + "%");
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
      }



      values.forEach(function(valor, index) {
        table.find('[class="split' + (index + 1) + '"]').val(valor)
      });

      table.appendTo('#abc');

      var oldVal = $('#somaTabelaIE').val();
      $('#somaTabelaIE').val(eval(oldVal || 0) + eval(tTotal));

    } else {

      tTotal = values[3] * $("#dias").val();
      var oldVal = $('#somaTabelaIE').val();
      $('#somaTabelaIE').val(oldVal - eval(tTotal));

      //remove a table que pertence ao checkbox
      $("table#tabelaIE" + $(this).data('qty')).remove();
    }
    $(".recalcula").click();
  }).change();




});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tab_cliente"></div>
<input type="radio" class="situacao" name="situacao" id="situacao_reserva" value="R" disabled /> Reserva
<input type="radio" class="situacao" name="situacao" id="situacao_saida" value="S" checked />Saída
<input type="radio" class="situacao" name="situacao" id="situacao_chegada" value="C" />Chegada

<p>
  dataIni: <input name="dataIni" type="text" id="data_ini" value="01/04/2019 08:00" /> 
  dataFim: <input name="dataFim" type="text" id="data_fim" value="03/04/2019 08:00" /> 
  Dias: <input type="text" id="dias" style="width: 50px">
</p>

<p>===============================================</p>
Total fatura: <input type="text" id="totalFatura" value="100.00" />
<p>===============================================</p>

<strong>OPTIONS:</strong>
<div id="D1">1.
  <input name="opcoes[]" class="c Obrig" type="checkbox" checked value="1|Taxa aluguel|ENC|15.00|FIX|POR|VLT|%" alt="15.00" title="Rental Rate" /> <b> Taxa aluguel </b>
</div>
<div id="D2">2.
  <input name="opcoes[]" class="c " type="checkbox" checked value="2|GPS|ENC|5.00|DIA|MON|DIA|" alt="5.00" title="GPS" /> GPS
</div>
<div id="D3">3.
  <input name="opcoes[]" class="c " type="checkbox" value="3|Lavagem carro|ENC|30.00|FIX|MON|VLT|" alt="30.00" title="Car wash" /> Lavagem carro
</div>
<div id="D4">4.
  <input name="opcoes[]" class="c " type="checkbox" checked value="4|Transfer|ENC|35.00|FIX|MON|VLT|" alt="35.00" title="Transfer" /> Transfer
</div>


<p>===============================================</p>
<table width="400" border="0">
  <tr>
    <td><b>TAXAS E SERVIÇOS</b></td>
  </tr>
  <tr>
    <td>
      <div id="abc">
        <table id="tabelaIE" width='400' border='0'>
          <tr>
            <td class="tNome" width='190px'></td>
            <td class="tDias" width='50px' align='center'></td>
            <td class="tValor" width='60px' align='right'></td>
            <td class="tTotal" width='100px' align='right'></td>
            <td class="tValores">
              <input type="hidden" class="split1" value="">
              <input type="hidden" class="split2" value="">
              <input type="hidden" class="split3" value="">
              <input type="hidden" class="split4" value="">
              <input type="hidden" class="split5" value="">
              <input type="hidden" class="split6" value="">
              <input type="hidden" class="split7" value="">
              <input type="hidden" class="split8" value="">
            </td>
          </tr>
        </table>
      </div>
    </td>
  </tr>
</table>
<p>===============================================</p>

SOMA DAS TAXAS E SERVIÇOS:
<input type="text" class="somaTabelaIE" id="somaTabelaIE" value="0">

  • 1

    That one Listener should help: document.querySelector('#situacao_chegada').addEventListener('change', () -> {//Blah});

  • The calculations are already working?

  • @Sam Yes, they are already working on my files, only here it does not work. When I remove the event $("#tab_cliente").on('mouseover', function() { works, but this only here, in my files works.

  • @Sam you can help me?

  • @Sam, if it’s too thorough to help, how much would you charge me to solve this problem?

  • When I get home I see for you

  • Fantastic, thank you very much @Sam

Show 2 more comments

1 answer

0

Create a separate function to calculate the total, do not do inside an event function because it complicates a lot. Note that I created the function somaTaxas() that goes through the last td’s of the table and adds up, then plays the result in the total input.

Also create an Event Handler blur and click in the elements #data_fim and #situacao_chegada that calls the calculation function and calls the other events that calculate the rates. See in the code below what has been added and removed.

$(document).ready(function() {

   var data = new Date();
   var dia = ("0" + data.getDate()).slice(-2);
   var mes = ("0" + (data.getMonth() + 1)).slice(-2);
   var ano4 = data.getFullYear();
   var hora = ("0" + data.getHours()).slice(-2);
   var min = ("0" + data.getMinutes()).slice(-2);
   var str_data = dia + '/' + mes + '/' + ano4;
   var str_hora = hora + ':' + min;

   $("#data_fim, #situacao_chegada").on("click blur", function(e){
      setTimeout(function(){
         $("#tab_cliente").mouseover();
         $('#abc table:not(:first)').remove();
         $(".c").change();
         somaTaxas();
      }, 100);
   });

   $("input[name=situacao]").on('change', function() {
      
      if ($(this).val() == "S") {

         $("#data_ini").attr({
            "readonly": true,
            "disabled": true
         });
   
         $('#tab-kmUsado').hide();

      } else if ($(this).val() == "C") {

         $("#data_fim").attr({
            "readonly": true,
            "disabled": true
         }).val(str_data + " " + str_hora);
         $("#situacao_saida").attr("disabled", false);
         $("#tab_cliente").mouseover();
         $('#tab-avisoKmUsado').hide();
         $('#tab-kmUsado').show();

      if ($("#selectPlano").val() == "KL") {

        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_dia_kmlivre").val());
        var planoTotal = $("#dias").val() * $("#valor_dia_kmlivre").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("#selectPlano").val() == "KMC") {
        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_diaria_controlada").val());
        var planoTotal = $("#dias").val() * $("#valor_diaria_controlada").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("#selectPlano").val() == "DI") {
        $("#planoDia").html($("#dias").val());
        $("#planoValor").html($("#valor_diaria").val());
        var planoTotal = $("#dias").val() * $("#valor_diaria").val();
        $("#planoTotal").html(planoTotal.toFixed(2));
        $(".planoTotal").val(planoTotal.toFixed(2));
      }

      if ($("input[type=radio][name='seguroCarro']:checked").val() == "S") {
        $("#SegCarroS2").html($("#dias").val());
        $("#SegCarroS3").html($("#val_seguro_carro").val());
        var seguroV = $("#dias").val() * $("#val_seguro_carro").val();
        $("#SegCarroS4").html(seguroV.toFixed(2));
        $(".SegCarroS4").val(seguroV.toFixed(2));
      } else {
        $("#SegCarroS2, #SegCarroS3").html("0");
        $("#SegCarroS4").html("0.00");
        $(".SegCarroS4").val("0.00");
      }

      if ($("input[type=radio][name='seguroTerceiros']:checked").val() == "S") {
        $("#SegTerceirosT2").html($("#dias").val());
        $("#SegTerceirosT3").html($("#val_seguro_terceiros").val());
        var seguroT = $("#dias").val() * $("#val_seguro_terceiros").val();
        $("#SegTerceirosT4").html(seguroT.toFixed(2));
        $(".SegTerceirosT4").val(seguroT.toFixed(2));
      } else {
        $("#SegTerceirosT2, #SegTerceirosT3").html("0");
        $("#SegTerceirosT4").html("0.00");
        $(".SegTerceirosT4").val("0.00");
      }


      $(".recalcula").click();

    } else {

    }
  }).parent().find("input[name=situacao]:checked").change();

  $("#tab_cliente").on('mouseover', function() {
    DAY = 1000 * 60 * 60 * 24;

    var data_ini = $("#data_ini").val().toString().split('/');
    data_ini2 = data_ini[1] + "/" + data_ini[0] + "/" + data_ini[2];
    d1 = new Date(data_ini2);

    var data_fim = $("#data_fim").val().toString().split('/');
    data_fim2 = data_fim[1] + "/" + data_fim[0] + "/" + data_fim[2];
    d2 = new Date(data_fim2);

    $("#data_ini2").val($("#data_ini").val());

    var diasLocacao = Math.round((d2.getTime() - d1.getTime()) / DAY);

    $("#dias").val(diasLocacao);

  }).mouseover();


  $(".c").on('change', function() {

   
    var values = $(this).val().split('|');
    if ($(this).prop('checked')) {

      var quantity = $("table[id^=tabelaIE]").length;

      $(this).data('qty', quantity);

      var table = $("#tabelaIE").clone(true)
        .attr('id', function() {
          return this.id + quantity;
        })
        .find(':text,:file')
        .attr('id', function() {
          return this.id + quantity;
        })
        .val("")
        .end();

      //VALUE -> 1|Taxa de locação|ENC|15.00|FIX|POR|VLT|%
      //$ID_ImpEnc|$nome|$tipo|$valor|$calculo|$valor_em|$aplicacao|$a

      //APLICAÇÃO: [SEG] Sobre seguro, [KML] KmLivre, [DIA] Diária, [IE] Impostos/Encargos, [VLT] no valor total
      //VALOR EM.: [MOT] Montante, [POR] Porcentagem.
      //CALCULO..: [DIA]Por dia, [FIX]Fixo
      //TIPO.....: [TXV]Taxa de Venda, [ENC]Encargos Extras

      aplicacao = values[6];
      valor_em = values[5];
      calculo = values[4];
      tipo = values[2];

      if (valor_em == "MON" && calculo == "FIX") {
        table.find('.tNome').text(values[1]);
        table.find('.tDias').text("1");
        table.find('.tValor').text(values[3]);
        tTotal = values[3] * 1;
        table.find('.tTotal').text(tTotal.toFixed(2));
      }

      if (valor_em == "MON" && calculo == "DIA") {
        table.find('.tNome').text(values[1]);
        table.find('.tDias').text($("#dias").val());
        table.find('.tValor').text(values[3]);
        tTotal = values[3] * $("#dias").val();
        table.find('.tTotal').text(tTotal.toFixed(2));
      }

      if (valor_em == "POR" && calculo == "FIX") {
        if (aplicacao == "SEG") {
          $V = (50 + 30) / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3]);
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "KML") {
          $V = values[3] / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3]);
          tTotal = values[3] - $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "DIA") {
          $V = (values[3] * $("#dias").val()) / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text($("#dias").val());
          table.find('.tValor').text(values[3]);
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
        if (aplicacao == "VLT") {
          $V = $("#totalFatura").val() / 100;
          table.find('.tNome').text(values[1]);
          table.find('.tDias').text("1");
          table.find('.tValor').text(values[3].substring(0, 2) + "%");
          tTotal = values[3] * $V;
          table.find('.tTotal').text(tTotal.toFixed(2));
        }
      }



//      values.forEach(function(valor, index) {
//        table.find('[class="split' + (index + 1) + '"]').val(valor)
//      });

      table.appendTo('#abc');
      //$("#data_fim, #situacao_chegada").blur();

//      var oldVal = $('#somaTabelaIE').val();
//      $('#somaTabelaIE').val(eval(oldVal || 0) + eval(tTotal));

    } else {

      tTotal = values[3] * $("#dias").val();
//      var oldVal = $('#somaTabelaIE').val();
//      $('#somaTabelaIE').val(oldVal - eval(tTotal));

      //remove a table que pertence ao checkbox
      $("table#tabelaIE" + $(this).data('qty')).remove();
    }
    $(".recalcula").click();
  }).change();

   function somaTaxas(){
      var soma = 0;
      $("#abc table:not(:first) .tTotal").each(function(){
         soma += parseFloat($(this).text());
      });
      $("#somaTabelaIE").val(soma.toFixed(2));
   }
    somaTaxas();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="tab_cliente"></div>
<input type="radio" class="situacao" name="situacao" id="situacao_reserva" value="R" disabled /> Reserva
<input type="radio" class="situacao" name="situacao" id="situacao_saida" value="S" checked />Saída
<input type="radio" class="situacao" name="situacao" id="situacao_chegada" value="C" />Chegada

<p>
  dataIni: <input name="dataIni" type="text" id="data_ini" value="01/04/2019 08:00" /> 
  dataFim: <input name="dataFim" type="text" id="data_fim" value="04/04/2019 08:00" /> 
  Dias: <input type="text" id="dias" style="width: 50px">
</p>

<p>===============================================</p>
Total fatura: <input type="text" id="totalFatura" value="300.00" />
<p>===============================================</p>

<strong>OPTIONS:</strong>
<div id="D1">1.
  <input name="opcoes[]" class="c Obrig" type="checkbox" checked value="1|Taxa aluguel|ENC|15.00|FIX|POR|VLT|%" alt="15.00" title="Rental Rate" /> <b> Taxa aluguel </b>
</div>
<div id="D2">2.
  <input name="opcoes[]" class="c " type="checkbox" checked value="2|GPS|ENC|5.00|DIA|MON|DIA|" alt="5.00" title="GPS" /> GPS
</div>
<div id="D3">3.
  <input name="opcoes[]" class="c " type="checkbox" value="3|Lavagem carro|ENC|30.00|FIX|MON|VLT|" alt="30.00" title="Car wash" /> Lavagem carro
</div>
<div id="D4">4.
  <input name="opcoes[]" class="c " type="checkbox" checked value="4|Transfer|ENC|35.00|FIX|MON|VLT|" alt="35.00" title="Transfer" /> Transfer
</div>


<p>===============================================</p>
<table width="400" border="0">
  <tr>
    <td><b>TAXAS E SERVIÇOS</b></td>
  </tr>
  <tr>
    <td>
      <div id="abc">
        <table id="tabelaIE" width='400' border='0'>
          <tr>
            <td class="tNome" width='190px'></td>
            <td class="tDias" width='50px' align='center'></td>
            <td class="tValor" width='60px' align='right'></td>
            <td class="tTotal" width='100px' align='right'></td>
            <td class="tValores">
              <input type="hidden" class="split1" value="">
              <input type="hidden" class="split2" value="">
              <input type="hidden" class="split3" value="">
              <input type="hidden" class="split4" value="">
              <input type="hidden" class="split5" value="">
              <input type="hidden" class="split6" value="">
              <input type="hidden" class="split7" value="">
              <input type="hidden" class="split8" value="">
            </td>
          </tr>
        </table>
      </div>
    </td>
  </tr>
</table>
<p>===============================================</p>

SOMA DAS TAXAS E SERVIÇOS:
<input type="text" class="somaTabelaIE" id="somaTabelaIE" value="0">

  • Hello Sam. To update the day FEES AND SERVICES have to click again on the screen? Could be calculated when clicked on radio Arrival?

  • I put in the answer, that part $("#data_fim, #situacao_chegada").on("blur click",

  • Hello Sam, good morning. A FEES AND SERVICES is only being when there is a click on the screen. Example: I click on arrival and then I have to click on the screen to update the GPS, which uses days parameter.

  • Good afternoon. Got it?

  • I think I get it. The "Blur" event is only triggered when it exits the date field. It adds one more event, "input", thus: "blur click input"

  • Put here $("#data_fim, #situacao_chegada").on("blur click", function(){? If it is, it seems that failed, I took the test and did not update.

  • Yes, along with Blur and click. Try adding another event, change: $("#data_fim, #situacao_chegada").on("blur click input change", function(){

  • It wasn’t. It only updates when I click on the screen.

  • Sam, you have skype?

  • Oops! I don’t have no :/

  • I’d like to know how much you’d charge to do this for me, I don’t have any money left, but I’m grateful you’ve helped me so far.

  • Sam, good afternoon. How much do you charge to make this part of the calculation work?

  • I got in, but it’s closed.

Show 9 more comments

Browser other questions tagged

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