javascript动态HTML表格行引起问题

时间:2019-07-02 06:46:27

标签: javascript jquery html html-table

我有一个select option,正在创建HTML表,因为我正在基于所选选项从后端调用数据,因此创建的表行是动态的

我在做什么

  • 在更改选择选项时,我正在创建HTML表格行,这些行是动态的,并且由输入字段组成,ItemName是自动完成的,因此当我选择任何项目名称并集中精力时,我都会该项目的一些对应值,并将其填充到其他“输入”字段中
  • 选择ItemName之后,我将注意力转移到pur. rate上,然后转移到UnitQty上,然后是Disc%,在这两者之间进行一些计算,最后,当我按{{1 }}我正在创建新行,并且新行的所有操作都相同

我的问题是什么

  • 在执行上述过程时,假设我正在下拉下拉选择的选项Disc%,但是后来我意识到我必须为另一个供应商这样做,也就是说这里是Supplier 1 ,因此在选择Supplier 2时,我要删除Supplier 2tbody并创建一个新的

  • 因此,在下拉更改之后创建了新行,它应该与上面的工作相同,但是对于第一行来说,它正在获取正确的数据,但是在tfoot上按Enter键创建新行会创建新行,但是Disc%正在获取其他供应商数据,例如ItemName正在第二行获取supplier 2数据

请检查我的提醒和评论摘要,以便更好地了解此问题

supplier 1
```
var CostPrice = "";
var totalAmount = "";
var unitQuantity = 0;
var unitQuantityOnDisc = 0;
var purchaseRateOnDisc = 0;
var purchaseRate = 0;
var totalAmount = "";
var discPercentage = "";
var discAmount = "";
var totalAmountOnDisc = "";
var subTotalOnDisc = 0;
var gstPercentage = "";
var gstAmount = "";
var totalAmountOnGst = "";
var total = 0;
var supplierCode = "";
var totalDiscountAmt = 0;
var totalGstAmt = 0;
var totalUnitQty = 0;
var subtotal = 0;
var totalAfterGrnDisc = 0;
var totalRoundOff = 0;
var totalAfterfreightAmt = 0;
var totalAftercommissionAmt = 0;
var mrpOnDisc = 0;
var tableData = {
  "ALMOND CHBAR~2402": {
    "itemName": "ALMOND CHBAR",
    "itemCode": "2402",
    "costPrice": 20.0,
    "gstPercentage": 14.5,
    "mrp": 30.0
  },
  "A BR SB EX~333": {
    "itemName": "A BR SB EX",
    "itemCode": "333",
    "costPrice": 1.0,
    "gstPercentage": 0.0,
    "mrp": 1.0
  }
}

var tableData1 = {
  "White rice~1001": {
    "itemName": "White rice",
    "itemCode": "1001",
    "costPrice": 50.0,
    "gstPercentage": 5,
    "mrp": 65.0
  },
  "Brown rice~333": {
    "itemName": "Brown rice",
    "itemCode": "1002",
    "costPrice": 90,
    "gstPercentage": 5.0,
    "mrp": 110
  }
}


$("#supplierInput").on("change", function(e) {
  $("tbody").empty();
  $("tfoot").empty();

  if (this.value == 'Supplier 1') {
    populateData(tableData)


  } else {
    populateData(tableData1)



  }

});

function populateData(data) {
  var autoCompleteData = Object.keys(data);

  function rowappend(tbody) {
    const markup =
      `<tr>
						  <td>
						    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
						  </td>
						  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
						  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
						  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
						  <td>
						    <input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
						  </td>
			               			 
						  <td>
						    <input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" >
						  </td>
						  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
						  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
						  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
						  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
						  <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>
						  
						</tr>`

    $(tbody).append(markup);
    setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

    $("[name=itemNametd]", tbody).last().autocomplete({
      source: autoCompleteData
    }).data('tableData', data); // <----   added...
  }

  function rowappendTfoot(tfoot) {

    const tfootmarkup =
      `<tr>
		<td id="itemNametf" class="commantf" align="center">Total ->
		</td>
		<td id="itemCodetf" class="commantf"></td>
		<td id="mrptf" class="commantd"></td>
		<td id="purRatetf" class="commantf"></td>
		<td id="unitQtytf" class="commantf"></td>
		<td id="discPercentagetf" class="commantf"></td>
		<td id="discAmttf" class="commantf"></td>
		<td id="gstPercentagetf" class="commantf"></td>
		<td id="gstAmttf" class="commantf"></td>
		<td id="totalAmttf" class="commantf"></td>
		<td id="crossBtntf" class="commantf"></td>
	</tr>`

    $(tfoot).append(tfootmarkup);

  }


  rowappend($('tbody', '#tableInvoice'))
  rowappendTfoot($('tfoot', '#tfootTable'))


  function getValues(row) {
    const search = ($('[name=itemNametd]', row).val()).toString()
    console.log("search  : " + search);
    var data = $('[name=itemNametd]', row).data('tableData'); // <--- added
    const value = data[search]; // this one is causing issue
    CostPrice = value.costPrice;

    if (value) {
      $(row).find("[name=itemCodetd]").val(value.itemCode);
      $(row).find("[name=mrptd]").val(value.mrp);
      $(row).find("[name=purRatetd]").val(CostPrice);

      $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
    }
  }

  function calc(row) {
    unitQuantity = $(row).find("[name=unitQtytd]").val() || '0';
    purchaseRate = $(row).find("[name=purRatetd]").val() || '0';
    var mrp = $(row).find("[name=mrptd]").text() || '0';
    totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));

    $(row).find("[name=totalAmttd]").val((totalAmount));

  }

  function calcDiscount(row) {
    unitQuantityOnDisc = $(row).find("[name=unitQtytd]").val() || '0';
    purchaseRateOnDisc = $(row).find("[name=purRatetd]").val() || '0';
    mrpOnDisc = $(row).find("[name=mrptd]").val() || '0';
    subTotalOnDisc = (parseFloat(unitQuantityOnDisc) * parseFloat(purchaseRateOnDisc));
    discPercentage = $(row).find("[name=discPercentagetd]").val() || '0';
    gstPercentage = $(row).find("[name=gstPercentagetd]").val() || '0';

    discAmount = (parseFloat(discPercentage) / 100) * parseFloat(totalAmount);
    totalAmountOnDisc = (parseFloat(totalAmount) - parseFloat(discAmount))
    gstAmount = (parseFloat(gstPercentage) / 100) * parseFloat(totalAmountOnDisc);
    totalAmountOnGst = (parseFloat(totalAmountOnDisc) + parseFloat(gstAmount))
    total += parseFloat(totalAmountOnGst);
    totalDiscountAmt += parseFloat(discAmount);
    totalGstAmt += parseFloat(gstAmount);
    totalUnitQty += parseFloat(unitQuantity);
    subtotal += parseFloat(subTotalOnDisc);
    totalRoundOff = total - Math.round(total);


    $(row).find("[name=discAmttd]").val((discAmount));
    $(row).find("[name=gstAmttd]").val((gstAmount));
    $(row).find("[name=totalAmttd]").val((totalAmountOnGst));

    $("#unitQtytf").text((totalUnitQty));
    $("#discAmttf").text((totalDiscountAmt));
    $("#gstAmttf").text((totalGstAmt));
    $("#netAmtInput").val((total));
    $("#totalAmttf").text((total));
    $("#subTotalInput").val((subtotal));
    $("#itemAmtDiscinput").val((totalDiscountAmt));
    $("#taxAmtInput").val((totalGstAmt));
    //	  $("#roundOffAmtInput").val(format(totalRoundOff));


  }

  $(document).on('focusout', function(e) {
    const row = e.target.parentElement.parentElement
    if (e.target.matches("[name=itemNametd]")) {
      getValues(e.target.parentElement.parentElement)
      $("[name=purRatetd]").focus();
    }
  });


  $(document).keypress(function(event) { // here I am trying to create new row when enter is clicked
    const row = event.target.parentElement.parentElement
    if (event.target.matches('[name=discPercentagetd]')) {
      var keycode = event.keyCode || event.which;
      if (keycode == '13') {
        alert("presed")
        calcDiscount(event.target.parentElement.parentElement)
        if ($(row).parent().find('tr').length - $(row).index() === 1) {
          rowappend(event.target.parentElement.parentElement.parentElement)

          total = 0;
          totalDiscountAmt = 0;
          totalGstAmt = 0;
          totalUnitQty = 0;
          subtotal = 0;

          $("#tableInvoice tbody tr").each(function() {
            calc(this)
            calcDiscount(this)
          })
        }
      }
    }





  });
  document.addEventListener("keydown", function(e) {

    const row = e.target.parentElement.parentElement
    if (event.target.matches('[name=discPercentagetd]') || e.target.matches('[name=unitQtytd]')) {

      var keycode = e.keyCode || event.e;
      if (keycode == '9') {


        if (!$(event.target).val()) {
          e.preventDefault();
          return;
        }


        total = 0;
        totalDiscountAmt = 0;
        totalGstAmt = 0;
        totalUnitQty = 0;
        subtotal = 0;

        $("#tableInvoice tbody tr").each(function() {
          calc(this)
          calcDiscount(this)
        })


      }

    }


  });
  $("#clear").click(function(e) {


    $("tbody").empty();
    $("tfoot").empty();
    $('#supplierInput option').prop('selected', function() {
      return this.defaultSelected;
    });
  });


}

这是我的动态代码,供那些误解它的人使用

要填充供应商<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" /> <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" /> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <div class="container commonDivInvoice"> <div class="form-row"> <div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-2"> <label for="supplierInput">Supplier</label> <select name="supplierInput" id="supplierInput" class="form-control"> <option disabled="disabled" selected="true">select supplier </option> <option>Supplier 1</option> <option>Supplier 2</option> </select> </div> </div> <div class="row tableInvoice" id="commonDvScroll"> <table class="table table-bordered" id="tableInvoice"> <thead> <tr> <th id="itemNameth" class="commanth">Item Name</th> <th id="itemCodeth" class="commanth">Code</th> <th id="mrpth" class="commanth">Mrp</th> <th id="purRateth" class="commanth">Pur.Rate</th> <th id="unitQtyth" class="commanth">Unit Qty</th> <th id="discPercentageth" class="commanth">Disc%</th> <th id="discAmtth" class="commanth">Disc Amt</th> <th id="gstPercentageth" class="commanth">Gst%</th> <th id="gstAmtth" class="commanth">Gst Amt</th> <th id="totalAmtth" class="commanth">Total Amount</th> </tr> </thead> <tbody> </tbody> </table> </div> <div class="row"> <table class="table table-bordered" id="tfootTable"> <tfoot> </tfoot> </table> </div> <button type="button" class="commonButton" id="clear"> <i class="fa fa-eraser"></i> Clear </button> </div>

Select option

因此,一旦填充了供应商,我就从下拉列表中选择一个,然后像下面这样调用ajax

$.ajax({
        'url': 'SupplierName', 
        'method' : "GET",
        'dataType' : "json",
        'contentType': "application/json; charset=utf-8",
        'success': function(SupplierNamedata){
            let dropdown = $('#supplierInput');
            dropdown.empty();
            dropdown.append('<option selected="true" disabled>Select Supplier</option>');
            dropdown.prop('selectedIndex', 0);
          $.each(SupplierNamedata, function (key, entry) {
            dropdown.append($('<option></option>').attr('value', entry.SupplierCode).text(entry.SupplierName));
        });

        },
        'error': function(err){ 

        } 
    });

`` 因此,通过上述代码,我正在动态地执行以下操作:首先用供应商名称填充选择选项 $("#supplierInput").on("change", function(e) { var supplierInvNo = $("#supplierInvNoInput").val(); $('#grnReceivingForm input[type="text"]').val(''); $('#grnReceivingForm input[type="tel"]').val('0.00'); $("tbody").empty(); $("tfoot").empty(); supplierCode = this.value $.ajax({ url: "dataToPopulate", method: "GET", dataType: "json", data: { supplierCode : supplierCode // sending supplier code }, contentType: "application/json; charset=utf-8", success: function(tabledata) { $("#tfootTable").show(); populateData(tabledata) }, }); ,而不是更改供应商时,我从该供应商的后端调用数据,并且drop-down每次更新时供应商已更改

2 个答案:

答案 0 :(得分:1)

问题出在所有地方全局使用的数据对象。 可以通过在运行时中基于选定的下拉菜单再次获取对象来进行处理。

请检查以下代码

    var CostPrice = "";
    var totalAmount = "";
    var unitQuantity = 0;
    var unitQuantityOnDisc = 0;
    var purchaseRateOnDisc = 0;
    var purchaseRate = 0;
    var totalAmount = "";
    var discPercentage = "";
    var discAmount = "";
    var totalAmountOnDisc = "";
    var subTotalOnDisc = 0;
    var gstPercentage = "";
    var gstAmount = "";
    var totalAmountOnGst = "";
    var total = 0;
    var supplierCode = "";
    var totalDiscountAmt = 0;
    var totalGstAmt = 0;
    var totalUnitQty = 0;
    var subtotal = 0;
    var totalAfterGrnDisc = 0;
    var totalRoundOff = 0;
    var totalAfterfreightAmt = 0;
    var totalAftercommissionAmt = 0;
    var mrpOnDisc = 0;
    var tableData = {
      "ALMOND CHBAR~2402": {
        "itemName": "ALMOND CHBAR",
        "itemCode": "2402",
        "costPrice": 20.0,
        "gstPercentage": 14.5,
        "mrp": 30.0
      },
      "A BR SB EX~333": {
        "itemName": "A BR SB EX",
        "itemCode": "333",
        "costPrice": 1.0,
        "gstPercentage": 0.0,
        "mrp": 1.0
      }
    }

    var tableData1 = {
      "White rice~1001": {
        "itemName": "White rice",
        "itemCode": "1001",
        "costPrice": 50.0,
        "gstPercentage": 5,
        "mrp": 65.0
      },
      "Brown rice~333": {
        "itemName": "Brown rice",
        "itemCode": "1002",
        "costPrice": 90,
        "gstPercentage": 5.0,
        "mrp": 110
      }
    }

    var tableDataGlob = ''; //global object
    $("#supplierInput").on("change", function (e) {
      $("tbody").empty();
      $("tfoot").empty();
      if (this.value == 'Supplier 1') {
        tableDataGlob = tableData;
        populateData(tableDataGlob)
      } else {
        tableDataGlob = tableData1;
        populateData(tableDataGlob)
      }
    });


    function populateData(data) {

      function rowappend(tbody) {
        const markup =
          `<tr>
                  <td>
                    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
                  </td>
                  <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
                  <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
                  <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
                  <td>
                    <input type="tel" id="unitQtytd"class="form-control commanChange unitQtytd" name="unitQtytd">
                  </td>
                              
                  <td>
                    <input type="tel" id="discPercentagetd" class="form-control commanChange discPercentagetd" name="discPercentagetd" >
                  </td>
                  <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
                  <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
                  <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
                  <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
                  <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>
                  
                </tr>`

        $(tbody).append(markup);
        setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);
        // Fetch Data on basis of dynamic Selected option 
        // Previously the code was declaring global var 2019-07-04 15:24:28
        var autoCompleteData = Object.keys(tableDataGlob);
      

        console.log(autoCompleteData);
        console.log($("[name=itemNametd]", tbody).last());
        $("[name=itemNametd]", tbody).last().autocomplete({
          source: autoCompleteData
        }).data('tableData', data); // <----   added...

      }

      function rowappendTfoot(tfoot) {

        const tfootmarkup =
          `<tr>
        <td id="itemNametf" class="commantf" align="center">Total ->
        </td>
        <td id="itemCodetf" class="commantf"></td>
        <td id="mrptf" class="commantd"></td>
        <td id="purRatetf" class="commantf"></td>
        <td id="unitQtytf" class="commantf"></td>
        <td id="discPercentagetf" class="commantf"></td>
        <td id="discAmttf" class="commantf"></td>
        <td id="gstPercentagetf" class="commantf"></td>
        <td id="gstAmttf" class="commantf"></td>
        <td id="totalAmttf" class="commantf"></td>
        <td id="crossBtntf" class="commantf"></td>
      </tr>`

        $(tfoot).append(tfootmarkup);

      }


      rowappend($('tbody', '#tableInvoice'))
      rowappendTfoot($('tfoot', '#tfootTable'))


      function getValues(row) {
        const search = ($('[name=itemNametd]', row).val()).toString()
        console.log("search  : " + search);
        
        var data = tableDataGlob;
        console.log(tableDataGlob);
    
        const value = data[search]; // this one is causing issue
        CostPrice = value.costPrice;

        if (value) {
          $(row).find("[name=itemCodetd]").val(value.itemCode);
          $(row).find("[name=mrptd]").val(value.mrp);
          $(row).find("[name=purRatetd]").val(CostPrice);

          $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
        }
      }

      function calc(row) {
        console.log(row)
        unitQuantity = $(row).find("[name=unitQtytd]").val() || '0';
        purchaseRate = $(row).find("[name=purRatetd]").val() || '0';
        var mrp = $(row).find("[name=mrptd]").text() || '0';
        totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));

        $(row).find("[name=totalAmttd]").val((totalAmount));

      }

      function calcDiscount(row) {
        unitQuantityOnDisc = $(row).find("[name=unitQtytd]").val() || '0';
        purchaseRateOnDisc = $(row).find("[name=purRatetd]").val() || '0';
        mrpOnDisc = $(row).find("[name=mrptd]").val() || '0';
        subTotalOnDisc = (parseFloat(unitQuantityOnDisc) * parseFloat(purchaseRateOnDisc));
        discPercentage = $(row).find("[name=discPercentagetd]").val() || '0';
        gstPercentage = $(row).find("[name=gstPercentagetd]").val() || '0';

        discAmount = (parseFloat(discPercentage) / 100) * parseFloat(totalAmount);
        totalAmountOnDisc = (parseFloat(totalAmount) - parseFloat(discAmount))
        gstAmount = (parseFloat(gstPercentage) / 100) * parseFloat(totalAmountOnDisc);
        totalAmountOnGst = (parseFloat(totalAmountOnDisc) + parseFloat(gstAmount))
        total += parseFloat(totalAmountOnGst);
        totalDiscountAmt += parseFloat(discAmount);
        totalGstAmt += parseFloat(gstAmount);
        totalUnitQty += parseFloat(unitQuantity);
        subtotal += parseFloat(subTotalOnDisc);
        totalRoundOff = total - Math.round(total);


        $(row).find("[name=discAmttd]").val((discAmount));
        $(row).find("[name=gstAmttd]").val((gstAmount));
        $(row).find("[name=totalAmttd]").val((totalAmountOnGst));

        $("#unitQtytf").text((totalUnitQty));
        $("#discAmttf").text((totalDiscountAmt));
        $("#gstAmttf").text((totalGstAmt));
        $("#netAmtInput").val((total));
        $("#totalAmttf").text((total));
        $("#subTotalInput").val((subtotal));
        $("#itemAmtDiscinput").val((totalDiscountAmt));
        $("#taxAmtInput").val((totalGstAmt));
        //	  $("#roundOffAmtInput").val(format(totalRoundOff));


      }

      $(document).on('focusout', function (e) {
        const row = e.target.parentElement.parentElement
        if (e.target.matches("[name=itemNametd]")) {
          console.log(e.target.parentElement.parentElement);
          getValues(e.target.parentElement.parentElement)
          $("[name=purRatetd]").focus();
        }
      });

      // $('.discPercentagetd').unbind();
      
      $('body').on('keypress','.discPercentagetd',function (event) { // here I am trying to create new row when enter is clicked
        const row = event.target.parentElement.parentElement
        if (event.target.matches('[name=discPercentagetd]')) {
          var keycode = event.keyCode || event.which;
          console.log(keycode);
          if (keycode == '13') {
            alert("presed")
            calcDiscount(event.target.parentElement.parentElement)
            if ($(row).parent().find('tr').length - $(row).index() === 1) {
              rowappend(event.target.parentElement.parentElement.parentElement)

              total = 0;
              totalDiscountAmt = 0;
              totalGstAmt = 0;
              totalUnitQty = 0;
              subtotal = 0;

              $("#tableInvoice tbody tr").each(function () {
                calc(this)
                calcDiscount(this)
              })
            }
          }
        }


      });


      $('body').on('keypress','.discPercentagetd,.unitQtytd', function (e) {

        const row = e.target.parentElement.parentElement
        if (event.target.matches('[name=discPercentagetd]') || e.target.matches('[name=unitQtytd]')) {

          var keycode = e.keyCode || event.e;
          if (keycode == '9') {


            if (!$(event.target).val()) {
              e.preventDefault();
              return;
            }


            total = 0;
            totalDiscountAmt = 0;
            totalGstAmt = 0;
            totalUnitQty = 0;
            subtotal = 0;

            $("#tableInvoice tbody tr").each(function () {
              calc(this)
              calcDiscount(this)
            })


          }

        }


      });

      $("#clear").unbind();
      $("#clear").click(function (e) {


        $("tbody").empty();
        $("tfoot").empty();
        $('#supplierInput option').prop('selected', function () {
          return this.defaultSelected;
        });
      });

    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet" />
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <div class="container commonDivInvoice">
      <div class="form-row">

        <div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-2">
          <label for="supplierInput">Supplier</label>
          <select name="supplierInput" id="supplierInput" class="form-control">
            <option disabled="disabled" selected="true">select supplier
            </option>
            <option>Supplier 1</option>
            <option>Supplier 2</option>

          </select>
          <input type="hidden" id="selectedtable" name="" value="">
        </div>





      </div>
      <div class="row tableInvoice" id="commonDvScroll">
        <table class="table table-bordered" id="tableInvoice">
          <thead>
            <tr>
              <th id="itemNameth" class="commanth">Item Name</th>
              <th id="itemCodeth" class="commanth">Code</th>
              <th id="mrpth" class="commanth">Mrp</th>
              <th id="purRateth" class="commanth">Pur.Rate</th>
              <th id="unitQtyth" class="commanth">Unit Qty</th>
              <th id="discPercentageth" class="commanth">Disc%</th>
              <th id="discAmtth" class="commanth">Disc Amt</th>
              <th id="gstPercentageth" class="commanth">Gst%</th>
              <th id="gstAmtth" class="commanth">Gst Amt</th>
              <th id="totalAmtth" class="commanth">Total Amount</th>

            </tr>
          </thead>
          <tbody>

          </tbody>

        </table>

      </div>
      <div class="row">
        <table class="table table-bordered" id="tfootTable">
          <tfoot>


          </tfoot>
        </table>
      </div>
      <button type="button" class="commonButton" id="clear">
          <i class="fa fa-eraser"></i> Clear
        </button>
    </div>

在这里测试工作模块: https://jsfiddle.net/m4fb038x/

答案 1 :(得分:1)

更新
问题是,您在 populateData 函数中放置了 rowappend 函数。这总是导致每次添加一行时都会填充第一个表对象。 请检查我更新的文本片段并运行它。您将看到它的工作原理。


请检查我更新的代码段。在这里,我试图通过返回一个对象来模仿一个AJAX调用响应。将我的代码与原始代码进行比较,以了解更改:

                                           

        <div class="form-group col-xs-6 col-sm-6 col-md-6 col-lg-2">
            <label for="supplierInput">Supplier</label>
            <select name="supplierInput" id="supplierInput" class="form-control">
                <option disabled="disabled" selected="true">select supplier
                </option>
                <option>Supplier 1</option>
                <option>Supplier 2</option>

            </select>
        </div>





    </div>
    <div class="row tableInvoice" id="commonDvScroll">
        <table class="table table-bordered" id="tableInvoice">
            <thead>
                <tr>
                    <th id="itemNameth" class="commanth">Item Name</th>
                    <th id="itemCodeth" class="commanth">Code</th>
                    <th id="mrpth" class="commanth">Mrp</th>
                    <th id="purRateth" class="commanth">Pur.Rate</th>
                    <th id="unitQtyth" class="commanth">Unit Qty</th>
                    <th id="discPercentageth" class="commanth">Disc%</th>
                    <th id="discAmtth" class="commanth">Disc Amt</th>
                    <th id="gstPercentageth" class="commanth">Gst%</th>
                    <th id="gstAmtth" class="commanth">Gst Amt</th>
                    <th id="totalAmtth" class="commanth">Total Amount</th>

                </tr>
            </thead>
            <tbody>

            </tbody>

        </table>

    </div>
    <div class="row">
        <table class="table table-bordered" id="tfootTable">
            <tfoot>


            </tfoot>
        </table>
    </div>
    <button type="button" class="commonButton" id="clear">
        <i class="fa fa-eraser"></i> Clear
    </button>
</div>
<script>
    var CostPrice = "";
    var totalAmount = "";
    var unitQuantity = 0;
    var unitQuantityOnDisc = 0;
    var purchaseRateOnDisc = 0;
    var purchaseRate = 0;
    var totalAmount = "";
    var discPercentage = "";
    var discAmount = "";
    var totalAmountOnDisc = "";
    var subTotalOnDisc = 0;
    var gstPercentage = "";
    var gstAmount = "";
    var totalAmountOnGst = "";
    var total = 0;
    var supplierCode = "";
    var totalDiscountAmt = 0;
    var totalGstAmt = 0;
    var totalUnitQty = 0;
    var subtotal = 0;
    var totalAfterGrnDisc = 0;
    var totalRoundOff = 0;
    var totalAfterfreightAmt = 0;
    var totalAftercommissionAmt = 0;
    var mrpOnDisc = 0;
    var tableData = {};

    // ---- This block is to mimic jQuery API call response. I am using your own data ---- //

    sellersList = [
        {
            "SupplierCode": "0001",
            "SupplierName": "Amazon"
        },
        {
            "SupplierCode": "0002",
            "SupplierName": "FlipKart"
        },
        {
            "SupplierCode": "0003",
            "SupplierName": "eBay"
        }
    ];

    listOfItemsBySellerCode = {
        "0001" : {
            "ALMOND CHBAR" : {
                "itemName": "ALMOND CHBAR",
                "itemCode": "2402",
                "costPrice": 20.0,
                "gstPercentage": 14.5,
                "mrp": 30.0
            },
            "A BR SB EX~333" : {
                "itemName": "A BR SB EX~333",
                "itemCode": "333",
                "costPrice": 1.0,
                "gstPercentage": 0.0,
                "mrp": 20.0
            }
        },
        "0002" : {
            "iPhone SE": {
                "itemName": "iPhone SE",
                "itemCode": "2001",
                "costPrice": 15700.0,
                "gstPercentage": 14.5,
                "mrp": 20000.0
            },
            "Remi Note 5": {
                "itemName": "Remi Note 5",
                "itemCode": "2095",
                "costPrice": 25000.0,
                "gstPercentage": 13.0,
                "mrp": 28745.0
            }
        },
        "0003" : {
            "Levi's Jeans": {
                "itemName": "Levi's Jeans",
                "itemCode": "1309",
                "costPrice": 3750.0,
                "gstPercentage": 14.5,
                "mrp": 4120.0
            },
            "Fastrack M135": {
                "itemName": "Fastrack M135",
                "itemCode": "3401",
                "costPrice": 6789.0,
                "gstPercentage": 9.06,
                "mrp": 7459.0
            }
        }

    }

    function ajax_response_for_sellers_list (response) {
        return function (params) {
            params.success(sellersList);
        };
    }

    function ajax_response_for_items_sold_by_seller (response) {
        return function (params) {
            params.success(listOfItemsBySellerCode[params.data.supplierCode])
        }
    }

    // ****** Custom API response block ends here ******* //


    // Populate Supplier select options

    // Here I'm telling $.ajax to return with the seller data which I already have in my variable (for now). This way I don't even need to fire the API. 
    // But you can assume your API will respond in this JSON structure
    $.ajax = ajax_response_for_sellers_list();

    $.ajax({
        'url': '/mockAPI/to/get/suppliersData',
        'method': "GET",
        'dataType': "json",
        'contentType': "application/json; charset=utf-8",
        'success': function (response) {
            console.log('Our Mock API responding with list of all sellers : ')
            console.log(response);

            let dropdown = $('#supplierInput');
            dropdown.empty();
            dropdown.append('<option selected="true" disabled>Select Supplier</option>');
            dropdown.prop('selectedIndex', 0);
            $.each(response, function (key, entry) {
                dropdown.append($('<option></option>').attr('value', entry.SupplierCode).text(entry.SupplierName));
            });

        },
        'error': function (err) {

        }
    });

    // Here I'm telling $.ajax to return all items sold by a seller (seller is identified by code)
    // You can assume your API will respond in this JSON structure
    $.ajax = ajax_response_for_items_sold_by_seller();

    $("#supplierInput").on("change", function (e) {
        var supplierInvNo = $("#supplierInvNoInput").val();
        $('#grnReceivingForm input[type="text"]').val('');
        $('#grnReceivingForm input[type="tel"]').val('0.00');
        $("tbody").empty();
        $("tfoot").empty();

        supplierCode = jQuery(this).find(":selected").val();
        $('.loader').show();
        $('.overlay').show();
        $.ajax({

            url: "/mockAPI/to/get/items/based/on/sellercode",
            method: "POST",
            dataType: "json",
            data: {
                supplierCode: supplierCode  // sending supplier code
            },
            contentType: "application/json; charset=utf-8",
            success: function (response) {

                console.log('Our Mock API responding with all items sold by the selected seller : ', supplierCode)
                console.log(response);

                $("#tfootTable").show();
                populateData(response)
            },
        });
    });

    function rowappend(tbody) {
        const markup =
            `<tr>
                <td>
                    <input type="text" class="form-control commanChange" id="itemNametd" name="itemNametd">
                </td>
                <td><input type="text" name="itemCodetd" id="itemCodetd" class="form-control commantd" readonly="readonly"></td>
                <td><input type="text" name="mrptd" id="mrptd" class="form-control commantd" readonly="readonly"></td>
                <td><input type="text" name="purRatetd" id="purRatetd" class="form-control commantd"></td>
                <td>
                    <input type="tel" id="unitQtytd"class="form-control commanChange" name="unitQtytd">
                </td>

                <td>
                    <input type="tel" id="discPercentagetd"class="form-control commanChange" name="discPercentagetd" >
                </td>
                <td><input type="text" name="discAmttd" id="discAmttd" class="form-control commantd" readonly="readonly"></td> 
                <td><input type="text" name="gstPercentagetd" id="gstPercentagetd" class="form-control commantd" readonly="readonly"></td>
                <td><input type="text" name="gstAmttd" id="gstAmttd" class="form-control commantd" readonly="readonly"></td>
                <td><input type="text" name="totalAmttd" id="totalAmttd" class="form-control commantd" readonly="readonly"></td>
                <td style="background-color: white;border: 1px white"><i class="fas fa-times fa-2x remove-btn"></i></td>

            </tr>`

        $(tbody).append(markup);
        setTimeout(() => $("[name=itemNametd]", tbody).last().focus(), 100);

        // Bind autocomplete data
        var autoCompleteData = Object.keys(tableData);
        $("[name=itemNametd]", $('tbody', '#tableInvoice')).last().autocomplete({
            source: autoCompleteData
        }).data('tableData', tableData); // <----   added...
    }

    function getValues(row) {
        const search = ($('[name=itemNametd]', row).val()).toString()
        console.log("search  : " + search);
        var data = $('[name=itemNametd]', row).data('tableData'); // <--- added
        const value = data[search]; // this one is causing issue

        // Check first if the user is selecting an `existing` data object
        if (value) {
            CostPrice = value.costPrice;

            if (value) {
                $(row).find("[name=itemCodetd]").val(value.itemCode);
                $(row).find("[name=mrptd]").val(value.mrp);
                $(row).find("[name=purRatetd]").val(CostPrice);

                $(row).find("[name=gstPercentagetd]").val(value.gstPercentage);
            }
        }
    }

    function calc(row) {
        unitQuantity = $(row).find("[name=unitQtytd]").val() || '0';
        purchaseRate = $(row).find("[name=purRatetd]").val() || '0';
        var mrp = $(row).find("[name=mrptd]").text() || '0';
        totalAmount = (parseFloat(unitQuantity) * parseFloat(purchaseRate));

        $(row).find("[name=totalAmttd]").val((totalAmount));

    }

    function calcDiscount(row) {
        unitQuantityOnDisc = $(row).find("[name=unitQtytd]").val() || '0';
        purchaseRateOnDisc = $(row).find("[name=purRatetd]").val() || '0';
        mrpOnDisc = $(row).find("[name=mrptd]").val() || '0';
        subTotalOnDisc = (parseFloat(unitQuantityOnDisc) * parseFloat(purchaseRateOnDisc));
        discPercentage = $(row).find("[name=discPercentagetd]").val() || '0';
        gstPercentage = $(row).find("[name=gstPercentagetd]").val() || '0';

        discAmount = (parseFloat(discPercentage) / 100) * parseFloat(totalAmount);
        totalAmountOnDisc = (parseFloat(totalAmount) - parseFloat(discAmount))
        gstAmount = (parseFloat(gstPercentage) / 100) * parseFloat(totalAmountOnDisc);
        totalAmountOnGst = (parseFloat(totalAmountOnDisc) + parseFloat(gstAmount))
        total += parseFloat(totalAmountOnGst);
        totalDiscountAmt += parseFloat(discAmount);
        totalGstAmt += parseFloat(gstAmount);
        totalUnitQty += parseFloat(unitQuantity);
        subtotal += parseFloat(subTotalOnDisc);
        totalRoundOff = total - Math.round(total);


        $(row).find("[name=discAmttd]").val((discAmount));
        $(row).find("[name=gstAmttd]").val((gstAmount));
        $(row).find("[name=totalAmttd]").val((totalAmountOnGst));

        $("#unitQtytf").text((totalUnitQty));
        $("#discAmttf").text((totalDiscountAmt));
        $("#gstAmttf").text((totalGstAmt));
        $("#netAmtInput").val((total));
        $("#totalAmttf").text((total));
        $("#subTotalInput").val((subtotal));
        $("#itemAmtDiscinput").val((totalDiscountAmt));
        $("#taxAmtInput").val((totalGstAmt));
        //    $("#roundOffAmtInput").val(format(totalRoundOff));


    }

    $(document).on('focusout', '[name=itemNametd]', function (e) {
        var row = jQuery(this).parent().parent();

        // Get row values
        getValues(row);

        // Focus next
        console.log('focusing next', row.find("[name=purRatetd]").length);
        row.find("[name=purRatetd]").focus();
    });


    $(document).keypress(function (event) { // here I am trying to create new row when enter is clicked
        const row = event.target.parentElement.parentElement
        if (event.target.matches('[name=discPercentagetd]')) {
            var keycode = event.keyCode || event.which;
            if (keycode == '13') {
                alert("presed")
                calcDiscount(event.target.parentElement.parentElement)
                if ($(row).parent().find('tr').length - $(row).index() === 1) {
                    rowappend(event.target.parentElement.parentElement.parentElement)

                    total = 0;
                    totalDiscountAmt = 0;
                    totalGstAmt = 0;
                    totalUnitQty = 0;
                    subtotal = 0;

                    $("#tableInvoice tbody tr").each(function () {
                        calc(this)
                        calcDiscount(this)
                    })
                }
            }
        }





    });
    document.addEventListener("keydown", function (e) {

        const row = e.target.parentElement.parentElement
        if (event.target.matches('[name=discPercentagetd]') || e.target.matches('[name=unitQtytd]')) {

            var keycode = e.keyCode || event.e;
            if (keycode == '9') {


                if (!$(event.target).val()) {
                    e.preventDefault();
                    return;
                }


                total = 0;
                totalDiscountAmt = 0;
                totalGstAmt = 0;
                totalUnitQty = 0;
                subtotal = 0;

                $("#tableInvoice tbody tr").each(function () {
                    calc(this)
                    calcDiscount(this)
                })


            }

        }


    });
    $("#clear").click(function (e) {
        $("tbody").empty();
        $("tfoot").empty();
        $('#supplierInput option').prop('selected', function () {
            return this.defaultSelected;
        });
    });

    function rowappendTfoot(tfoot) {

        const tfootmarkup =
            `<tr>
            <td id="itemNametf" class="commantf" align="center">Total ->
            </td>
            <td id="itemCodetf" class="commantf"></td>
            <td id="mrptf" class="commantd"></td>
            <td id="purRatetf" class="commantf"></td>
            <td id="unitQtytf" class="commantf"></td>
            <td id="discPercentagetf" class="commantf"></td>
            <td id="discAmttf" class="commantf"></td>
            <td id="gstPercentagetf" class="commantf"></td>
            <td id="gstAmttf" class="commantf"></td>
            <td id="totalAmttf" class="commantf"></td>
            <td id="crossBtntf" class="commantf"></td>
        </tr>`

        $(tfoot).append(tfootmarkup);

    }

    function populateData(data) {
        tableData = Object.assign({}, data);
        var autoCompleteData = Object.keys(data);
        rowappend($('tbody', '#tableInvoice'));
        rowappendTfoot($('tfoot', '#tfootTable'))
    }
</script>