所有输入字段的总和不是正确答案

时间:2018-12-03 09:55:02

标签: javascript jquery html arrays user-interface

var checkSum = 0;
var jsonData = {};
var pushData;
var trData = [];
var sumData = [];
var chkArray = [];

countTab2 = 1;
$(".add-customs").click(function() {
  customsTable();
});

function customsTable() {
  var markup = "<div class='col-md-1'>Custom</div>" +
    "<div class='col-md-4'><input id='customReason" +
    countTab2 +
    "' type='text' value='' class='txt form-control'" +
    "name='customReason' path='customReason' /></div>" +
    "<div class='col-md-2'><input value='0' type='text' class='txt form-control'" +
    "name='customAmount' id='customAmount" +
    countTab2 +
    "'></div>" +
    "<div class='col-md-2'><input value='0' onchange='getCustomTotal();' type='text' class='txt form-control'" +
    "name='customPenalty' id='customPenalty" +
    countTab2 +
    "'></div>" +
    "<div class='col-md-1'><span id='customSum" +
    countTab2 +
    "'>0</span></div>" +
    "<div class='col-md-2'></div>";
  countTab2++;
  $(".custom-table").append(markup);
}

//adding row for VAT
countTab3 = 1;
$(".add-vat").click(function() {
  vatTable();
});

function vatTable() {
  var markup = "<div class='col-md-1'>VAT</div>" +
    "<div class='col-md-4'><input id='vatReason" +
    countTab3 +
    "' type='text' value='' class='txt1 form-control'" +
    "name='vatReason' /></div>" +
    "<div class='col-md-2'><input type='text' class='txt1 form-control'" +
    "name='vatAmount' value='0' id='vatAmount" +
    countTab3 +
    "'></div>" +
    "<div class='col-md-2'><input type='text' value='0' onchange='getVatTotal();'  class='txt1 form-control'" +
    "name='vatPenalty' id='vatPenalty" +
    countTab3 +
    "'></div>" +
    "<div class='col-md-1'><span id='vatTotal" +
    countTab3 +
    "'></span></div>" +
    "<div class='col-md-2'></div>";
  countTab3++;
  $(".vat-table").append(markup);
}

//adding row for Excise
countTab4 = 1;
$(".add-excise").click(function() {
  exciseTable();
});

function exciseTable() {
  var markup = "<div class='col-md-1'>Excise</div>" +
    "<div class='col-md-4'><input id='exciseReason" +
    countTab4 +
    "' type='text' value='' class='txt2 form-control'" +
    "name='exciseReason' /></div>" +
    "<div class='col-md-2'><input type='text' class='txt2 form-control'" +
    "name='exciseAmount' value='0' id='exciseAmount" +
    countTab4 +
    "'></div>" +
    "<div class='col-md-2'><input type='text' onchange='getExciseTotal();' class='txt2 form-control'" +
    "name='excisePenalty' value='0' id='excisePenalty" +
    countTab4 +
    "'></div>" +
    "<div class='col-md-1'><span id='exciseTotal" +
    countTab4 +
    "'></span></div>" +
    "<div class='col-md-2'></div>";
  countTab4++;
  $(".excise-table").append(markup);
}

customs = [];

function getListCustoms() {

  for (i = 0; i < countTab2; i++) {
    if ($("#customPenalty" + i).length) {
      customs.push({
        assessReason: $("#customReason" + i).val(),
        assessAmount: $("#customAmount" + i).val(),
        assessPenalty: $("#customPenalty" + i).val()
      });
    }
  }
}

function getCustomTotal() {
  var customTotal = 0;
  getListCustoms();
  customs.unshift({
    assessReason: $("#customReason").val(),
    assessAmount: $("#customAmount").val(),
    assessPenalty: $("#customPenalty").val()
  });
  customTotal = customTotal + parseInt(customs[0].assessAmount) +
    parseInt(customs[0].assessPenalty);
  for (i = 1; i < customs.length; i++) {
    customTotal = customTotal + parseInt(customs[i].assessAmount) +
      parseInt(customs[i].assessPenalty);
    customRowTotal = 0;
    customRowTotal = parseInt($("#customAmount" + i).val()) +
      parseInt($("#customPenalty" + i).val());
    $("#customSum" + i).html(customRowTotal);
  }
  getTotalSum();
  $('#tot').html(wholeTotal);
}

$("#customPenalty").change(
  function() {
    totalCustom = 0;
    totalCustom = parseInt($("#customAmount").val()) +
      parseInt($("#customPenalty").val());
    $("#customSum").html(totalCustom);

  });

function getVatTotal() {
  var vatTotal = 0;
  getVatList();
  vats.unshift({
    assessReason: $("#vatReason").val(),
    assessAmount: $("#vatAmount").val(),
    assessPenalty: $("#vatPenalty").val()
  });
  vatTotal = vatTotal + parseInt(vats[0].assessAmount) +
    parseInt(vats[0].assessPenalty);
  for (i = 1; i < vats.length; i++) {
    vatTotal = vatTotal + parseInt(vats[i].assessAmount) +
      parseInt(vats[i].assessPenalty);
    vatRowTotal = 0;
    vatRowTotal = parseInt($("#vatAmount" + i).val()) +
      parseInt($("#vatPenalty" + i).val());
    $("#vatTotal" + i).html(vatRowTotal);
  }
  getTotalSum();
  $('#tot').html(wholeTotal);
}

$("#vatPenalty").change(
  function() {
    totalVat = 0;
    totalVat = parseInt($("#vatAmount").val()) +
      parseInt($("#vatPenalty").val());
    $("#vatTotal").html(totalVat);

  });

vats = [];

function getVatList() {
  for (i = 0; i < countTab3; i++) {
    if ($("#vatPenalty" + i).length) {
      vats.push({
        assessReason: $("#vatReason" + i).val(),
        assessAmount: $("#vatAmount" + i).val(),
        assessPenalty: $("#vatPenalty" + i).val()
      });
    }
  }
}

excises = [];

function getExciseList() {

  for (i = 0; i < countTab4; i++) {
    if ($("#excisePenalty" + i).length) {
      excises.push({
        assessReason: $("#exciseReason" + i).val(),
        assessAmount: $("#exciseAmount" + i).val(),
        assessPenalty: $("#excisePenalty" + i).val()
      });
    }
  }
}

$("#excisePenalty").change(
  function() {
    totalExcise = 0;
    totalExcise = parseInt($("#exciseAmount").val()) +
      parseInt($("#excisePenalty").val());
    /* $("#tot").html(totalVat+totalCustom); */
    $("#exciseTotal").html(totalExcise);

  });

function getExciseTotal() {
  var exciseTotal = 0;
  getExciseList();
  excises.unshift({
    assessReason: $("#exciseReason").val(),
    assessAmount: $("#exciseAmount").val(),
    assessPenalty: $("#excisePenalty").val()
  });
  exciseTotal = exciseTotal + parseInt(excises[0].assessAmount) +
    parseInt(excises[0].assessPenalty);
  for (i = 1; i < excises.length; i++) {
    exciseTotal = exciseTotal + parseInt(excises[i].assessAmount) +
      parseInt(excises[i].assessPenalty);
    exciseRowTotal = 0;
    exciseRowTotal = parseInt($("#exciseAmount" + i).val()) +
      parseInt($("#excisePenalty" + i).val());
    $("#exciseTotal" + i).html(exciseRowTotal);
  }
  getTotalSum();
  $('#tot').html(wholeTotal);
}

function getTotalSum() {
  wholeTotal = 0;
  var allList = customs.concat(vats, excises);
  for (i = 0; i < allList.length; i++) {
    wholeTotal += parseInt(allList[i].assessAmount) + parseInt(allList[i].assessPenalty);
  }
  console.log(wholeTotal);
}




//submit method now
$("form").submit(function() {
  event.preventDefault();
  getTotalSum();

});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form>
  <div class="col-md-12" style="float: none;">
    <!--  <button onclick="myFunction()" class="pull-right">+</button> -->
    <div style="margin-bottom: 30px;">
      <div class="form-group row">
        <div class="col-md-1"></div>
        <div class="col-md-4">
          <label>Reason</label>
        </div>
        <div class="col-md-2">
          <label>Amount</label>
        </div>
        <div class="col-md-2">
          <label>Penalty</label>
        </div>
        <div class="col-md-1">Total</div>
        <div class="col-md-2">Action</div>
      </div>
      <div class="custom-table row">
        <div class="col-md-1">
          <label>Customs</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control" id="customReason" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt" id="customAmount" value="0" name="abc" min="0" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt" id="customPenalty" onchange="getCustomTotal();" value="0" name="abc" min="0" />
        </div>
        <div class="col-md-1">
          <span id="customSum">0</span>
        </div>
        <div class="col-md-2">
          <button class="add-customs">+</button>
        </div>
      </div>
      <div class="vat-table row">
        <div class="col-md-1">
          <label>VAT</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control" id="vatReason" name="vatReason" />
        </div>
        <div class="col-md-2">
          <input type="text" class="form-control txt1" id="vatAmount" value="0" name="vatAmount" min="0" />
        </div>
        <div class="col-md-2">
          <input type="text" class="form-control txt1" id="vatPenalty" value="0" name="vatPenalty" onchange="getVatTotal();" min="0" />
        </div>
        <div class="col-md-1">
          <span id="vatTotal">0</span>
        </div>
        <div class="col-md-2">
          <button class="add-vat">+</button>
        </div>
      </div>
      <div class="excise-table row">
        <div class="col-md-1">
          <label>Excise</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control" id="exciseReason" name="exciseReason" />
        </div>
        <div class="col-md-2">
          <input type="text" class="form-control txt2" id="exciseAmount" value="0" name="exciseAmount" min="0" />
        </div>
        <div class="col-md-2">
          <input type="text" class="form-control txt2" id="excisePenalty" value="0" name="excisePenalty" onchange="getExciseTotal();" min="0" />
        </div>
        <div class="col-md-1">
          <span id="exciseTotal">0</span>
        </div>
        <div class="col-md-2">
          <button class="add-excise">+</button>
        </div>
        <div class="col-md-1 pull-right">
          <label>Total:</label> <b> <span id="tot">0</span></b>
        </div>
      </div>
    </div>
    <button type="submit" class="btn btn-success pull-right">Submit</button>
  </div>
</form>

我的表单看起来像这样:

enter image description here

成功显示了相应行的总数,但未按预期显示所有输入字段的总数。当我清除一个输入字段时,不会从总数中减去其数据。我无法获得所有动态输入字段的正确总和。我如何在这里进行更改?


更新:

当我在“金额”和“罚款”中键入一些数据时,总数也恰好在“罚款”列之后。

我可以像

那样将那些总数总计传递给数组吗?
{
 assessmentType: "PRE", 
 assessCatID: 1, 
 assessReason: "11", 
 assessAmount: "22", 
 assessPenalty: "33"
} 

我需要一个新字段customOneRowTotal:22 + 33,需要插入数组中

更新代码(2018年12月9日):

我有一个调用API的AJAX,它已成功到达控制台:

var table = $('#nepal')
        .DataTable(
                {
                    "processing" : true,
                    "ajax" : {
                        "url" : A_PAGE_CONTEXT_PATH
                                + "/form/api/getSelectionByAssessmentOrNonAssessment",
                        dataSrc : ''
                    },
                    "columns" : [ {
                        "data" : "selectionId"
                    }, {
                        "data" : "selectionDate"
                    }, {
                        "data" : "selectedBy"
                    }, {
                        "data" : "eximPanNo"
                    }, {
                        "data" : "eximPanName"
                    }, {
                        "data" : "eximPanAddr"
                    }, {
                        "data" : "eximPanPhone"
                    }, {
                        "data" : "selectionType"
                    }, {
                        "data" : "auditorGroupName"
                    } ]
                });

数据最近显示在数据表上,当我单击单行时,将其选中并填充为:

enter image description here

通过此Ajax调用获得的JSON数据为:(我们现在需要从整个JSON数据中获取最近的AssessmentCatAmount数据)

{  
   "selectionId":1,
   "selectionDate":"2075-08-15",
   "selectedBy":"Department",
   "eximPanNo":1234,
   "eximPanName":"PCS",
   "eximPanNameEng":"PCS",
   "eximPanAddr":"KAPAN",
   "eximPanAddrEng":"PCS",
   "eximPanPhone":9843709166,
   "selectionType":"consignment\r\n",
   "consignmentNo":122,
   "consignmentDate":"2018-2-6",
   "productName":null,
   "selectionFromDate":"2018-11-30",
   "selectionToDate":"2018-11-28",
   "agentNo":3,
   "selectionStatus":"1",
   "entryBy":"1",
   "entryDate":"2018-11-25 11:25:11",
   "rStatus":"1",
   "custOfficeId":1,
   "selectionAudit":null,
   "letter":null,
   "auditorGroupName":null,
   "document":null,
   "assessment":{  
      "assessmentNo":1,
      "assessmentType":"PRE",
      "offCode":null,
      "assessmentDate":"2071",
      "assessmentBy":null,
      "totalAssessment":null,
      "selectionId":1,
      "assSec":null,
      "assRule":null,
      "parentAssessmentId":null,
      "appealId":445,
      "demandNo":null,
      "eximCd":null,
      "consignmentNo":null,
      "assessFrom":null,
      "assessTo":null,
      "assessReason":null,
      "reasonDesc":null,
      "intCalUpto":"2070",
      "assessBasis":null,
      "entryBy":"PCS",
      "rStatus":"1"
   },
   "assessCatAmount":[  
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":1,
         "assessReason":"A",
         "assessAmount":1,
         "assessPenalty":2,
         "entryBy":"PCS",
         "rStatus":"1"
      },
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":1,
         "assessReason":"D",
         "assessAmount":3,
         "assessPenalty":4,
         "entryBy":"PCS",
         "rStatus":"1"
      },
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":2,
         "assessReason":"B",
         "assessAmount":5,
         "assessPenalty":6,
         "entryBy":"PCS",
         "rStatus":"1"
      },
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":2,
         "assessReason":"E",
         "assessAmount":7,
         "assessPenalty":8,
         "entryBy":"PCS",
         "rStatus":"1"
      },
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":3,
         "assessReason":"C",
         "assessAmount":9,
         "assessPenalty":10,
         "entryBy":"PCS",
         "rStatus":"1"
      },
      {  
         "assessmentNo":1,
         "assessmentType":"PRE",
         "assessCatId":3,
         "assessReason":"F",
         "assessAmount":10,
         "assessPenalty":10,
         "entryBy":"PCS",
         "rStatus":"1"
      }
   ]
}

现在我们的表单为:

enter image description here

现在,我需要将这六个assetCatAmount数据填充到此表中。我怎么得到这个?

当我单击数据表时,单击的行为是通过以下方式发生的:

.selected {
    background-color: #a7d8d3;
}

$('#nepal tbody').on('click', 'tr', function() {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
    } else {
        table.$('tr.selected').removeClass('selected');
        $(this).addClass('selected');
    }
    trDataSecondTable = table.row(this).data();
    console.log(trDataSecondTable);
});

点击数据表中的所有行,所有内容都存储在trDataSecondTable中。

$('#chooseButton')
        .on(
                'click',
                function() {
                    $('.hidden')
                            .css('display', 'block');
                    $("#panEximName")
                            .html(
                                    trDataSecondTable.eximPanNameEng);
                    $("#panEximPhone")
                            .html(
                                    trDataSecondTable.eximPanPhone);
                    for (var i = 0; i < trDataSecondTable.document.length; i++) {
                        if ($("#invoice").val() == trDataSecondTable.document[i].docNameEng) {
                            $("#invoice").prop(
                                    'checked', true);
                        } else if ($("#packingList")
                                .val() == trDataSecondTable.document[i].docNameEng) {
                            $("#packingList").prop(
                                    'checked', true);
                        } else {
                            $("#invoice").prop(
                                    'checked', false);
                            $("#packingList").prop(
                                    'checked', false);
                        }
                    }
                    $("#inoutDate")
                            .val(
                                    trDataSecondTable.letter[0].inoutDate);

                });

1 个答案:

答案 0 :(得分:1)

您需要委派而不使用内联事件处理

  1. 代理和克隆-我更改了div类以匹配风俗而不是自定义
  2. 每次更改的总和
  3. 将所有按钮更改为type="button",使其不提交到[+]
  4. 我将总计移出了消费税行

function sumIt() {
  $("#formContainer [type=number]").each(function() {
    var $row = $(this).closest(".row");
    var $fields = $row.find("[type=number]");
    var val1 = $fields.eq(0).val();
    var val2 = $fields.eq(1).val();
    var tot = (isNaN(val1) ? 0 : +val1) + (isNaN(val2) ? 0 : +val2)
    $row.find(".sum").text(tot);
  });
  var total = 0;
  $(".sum").each(function() {
    total += isNaN($(this).text()) ? 0 : +$(this).text()
  });
  $("#tot").text(total);
  return total;
}

$(".customs-table .remove:lt(1)").hide();  
$(".vat-table     .remove:lt(1)").hide();  
$(".excise-table  .remove:lt(1)").hide();  

$("#formContainer").on("click", "button", function() {
  var selector = "div.row";
  var $div = $(this).closest(selector);
  if ($(this).is(".add")) {
    var $newDiv = $div.clone();
    $newDiv.find(":input").val(""); // clear all
    $newDiv.find("[type=number]").val(0); // clear numbers
    $newDiv.find(".sum").text(0); // clear total
    $newDiv.insertAfter($div)
  }
  else {
    $div.remove();
     sumIt(); 
  }
  $(".customs-table .remove:gt(0)").show();  
  $(".vat-table     .remove:gt(0)").show();  
  $(".excise-table  .remove:gt(0)").show();  
});


$("#formContainer").on("input", "[type=number]", sumIt);

$("form").submit(function() {
  event.preventDefault();
  var user_profile = [];
  $(".row").each(function() {
    var $fields = $(this).find(":input");
    if ($fields.length > 0) {
      var cat = $(this).find("div>label").eq(0).text(); // use the label of the row
      var catId = ["","Customs","VAT","Excise"].indexOf(cat)
      user_profile.push({
        assessmentType: "PRE",
        assessCatID : catId, 
        assessReason: $fields.eq(0).val(),
        assessAmount: $fields.eq(1).val(),
        assessPenalty: $fields.eq(2).val(),
        assessTotal: +$fields.eq(1).val() + +$fields.eq(2).val() // the leading + makes it a number
      });
    }
  });
  console.log(user_profile);
  /*
  $.ajax({
    url: "someserverfunction",
    data: JSON.encode(user_profile),
    success : function(data) { }
    error: function() { }
  });  
  */
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<form id="myForm">
  <div id="formContainer" class="col-md-12" style="float: none;">
    <!--  <button onclick="myFunction()" class="pull-right">+</button> -->
    <div style="margin-bottom: 30px;">
      <div class="form-group row">
        <div class="col-md-1"></div>
        <div class="col-md-4">
          <label>Reason</label>
        </div>
        <div class="col-md-2">
          <label>Amount</label>
        </div>
        <div class="col-md-2">
          <label>Penalty</label>
        </div>
        <div class="col-md-1">Total</div>
        <div class="col-md-2">Action</div>
      </div>
      <div class="customs-table row">
        <div class="col-md-1">
          <label>Customs</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control customReason" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt customAmount" value="0" name="abc" min="0" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt customPenalty" value="0" name="abc" min="0" />
        </div>
        <div class="col-md-1">
          <span class="sum">0</span>
        </div>
        <div class="col-md-2">
          <button type="button" class="add">+</button>
          <button type="button" class="remove">-</button>
        </div>
      </div>
      <div class="vat-table row">
        <div class="col-md-1">
          <label>VAT</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control vatReason" name="vatReason" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt1 vatAmount" value="0" name="vatAmount" min="0" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt1 vatPenalty" value="0" name="vatPenalty" min="0" />
        </div>
        <div class="col-md-1">
          <span class="sum">0</span>
        </div>
        <div class="col-md-2">
          <button type="button" class="add">+</button>
          <button type="button" class="remove">-</button>
        </div>
      </div>
      <div class="excise-table row">
        <div class="col-md-1">
          <label>Excise</label>
        </div>
        <div class="col-md-4">
          <input type="text" class="form-control exciseReason" name="exciseReason" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt2 exciseAmount" value="0" name="exciseAmount" min="0" />
        </div>
        <div class="col-md-2">
          <input type="number" class="form-control txt2 excisePenalty" value="0" name="excisePenalty" min="0" />
        </div>
        <div class="col-md-1">
          <span class="sum">0</span>
        </div>
        <div class="col-md-2">
          <button type="button" class="add">+</button>
          <button type="button" class="remove">-</button>
        </div>
      </div>
      <div class="col-md-12 pull-right">
        <label>Total:</label>&nbsp;<b><span id="tot">0</span></b>
      </div>
    </div>
    <button type="submit" class="btn btn-success pull-right">Submit</button>
  </div>
</form>