javascript - 加载选中的复选框并计算它们

标签 javascript jquery html

我需要通过更改dataFim字段或单击单选按钮到达来重新计算费率和服务

请参阅下面的我的代码。在另一个链接中可以更好地查看所有字段:https://jsfiddle.net/yormgb5j/1/

非常感谢。

$(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 /> Reservation
<input type="radio" class="situacao" name="situacao" id="situacao_saida" value="S" checked />Output
<input type="radio" class="situacao" name="situacao" id="situacao_chegada" value="C" />Arrival

<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" /> 
  DAYS: <input type="text" id="dias" style="width: 50px">
</p>

<p>===============================================</p>
Invoice total: <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|Rental Rate|ENC|15.00|FIX|POR|VLT|%" alt="15.00" title="Rental Rate" /> <b> Rental Rate </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|Car wash|ENC|30.00|FIX|MON|VLT|" alt="30.00" title="Car wash" /> Car wash
</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>RATES AND SERVICES</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>

SUMMARY OF RATES AND SERVICES:
<input type="text" class="somaTabelaIE" id="somaTabelaIE" value="0">

最佳答案

更改:将事件添加到更改函数中,并跟踪事件是否冒泡(通过客户端点击进行属性更改或在 HTML 标记中设置默认值)。

查询:在取消选中逻辑中减去总金额,然后乘以天数而不是数量。

编辑:从与复选框(即未选中的复选框)相关的 html 表中获取总值(value)(金额 * 数量)。

编辑2:更改获取总金额的方法并简化 var Qty = $("#abc tr:contains('"+$(this).attr('title') +"').tTotal").text(); .编辑后的代码片段工作正常。

编辑3:更改ID生成逻辑var数量 = eval($("table[id^=tabelaIE]:last").attr('id').replace("tabelaIE","0"))+1.

编辑 4:更改新复选框输出和事件重新计算。

$(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() {
    $('#somaTabelaIE').val(""); 
    $('.tTotal:visible').each(function(){ $('#somaTabelaIE').val(Number($('#somaTabelaIE').val()) + Number(this.innerHTML))})
    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(e) {

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

        var quantity = eval($("table[id^=tabelaIE]:last").attr('id').replace("tabelaIE","0"))+1

        $(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 if(e.bubbles) {

        var Qty = $("#abc tr:contains('"+$(this).attr('title')+"') .tTotal").text();
        var oldVal = $('#somaTabelaIE').val();
        $('#somaTabelaIE').val(oldVal - eval(Qty));

        //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 /> Reservation
<input type="radio" class="situacao" name="situacao" id="situacao_saida" value="S" checked />Output
<input type="radio" class="situacao" name="situacao" id="situacao_chegada" value="C" />Arrival

<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" /> 
  DAYS: <input type="text" id="dias" style="width: 50px">
</p>

<p>===============================================</p>
Invoice total: <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|Rental Rate|ENC|15.00|FIX|POR|VLT|%" alt="15.00" title="Rental Rate" /> <b> Rental Rate </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|Car wash|ENC|30.00|FIX|MON|VLT|" alt="30.00" title="Car wash" /> Car wash
</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>RATES AND SERVICES</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>

SUMMARY OF RATES AND SERVICES:
<input type="text" class="somaTabelaIE" id="somaTabelaIE" value="0">

关于javascript - 加载选中的复选框并计算它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55376019/

相关文章:

javascript - 如何在Javascript中顺序调用Python连接:Node. js

javascript - 如何将这行 Jquery 转换为纯 Javascript?

JavaScript 错误 : Uncaught TypeError: Cannot read property 'value' of null

javascript - 整页 jQuery slider

javascript - 如何使用数组分配下拉选项值

html - 使用 html 敏捷包修复丢失的 HTML 标签

PHP 递归目录列表 - 仅目录

javascript - 有没有比 for 循环更好的方法将对象数组的属性添加到另一个数组?

javascript - 如何在 javascript 中使用正则表达式匹配精确的数字计数

javascript - 将对象的数组属性发送到 Ajax