动态创建的HTML表格行无法正常工作

时间:2019-07-01 13:09:26

标签: javascript jquery html

我有一个Select drop-down字段,因此在更改时,我将创建一个完全动态的HTML表行

我在做什么

  • 当用户更改创建Html表行的下拉选项时,第一列(即ItemName是自动完成的),用户可以键入并选择并着重进行一些计算
  • 这里有两个下拉菜单,因此当用户选择supplier 1加载JSON数据即tableData时,如果用户选择Supplier 2然后在tabledata1上工作,则必须定义我的代码中有两个JSON数据,我在更改事件上使用Ajax
  • 因此,当我首先选择Supplier 1时,如果使用$(tbody).empty存在任何行,然后删除一行,然后在ItemName字段中填充一行,则我正在执行自动完成并运行正常

问题是  -当我想更改供应商,现在我选择supplier 2并删除了Supplier 1的上一行,并且当我在自动完成字段中输入并着重注意时,它说value is not defined  -我不知道我在做什么错

要检查错误

  • 选择Supplier 1并输入333,然后从下拉菜单中进行选择,它将在相应字段中填充一些内容

  • 然后再次将下拉菜单从Supplier 1更改为Supplier 2并键入白色,它将显示建议,并选择按Tab聚焦在那里,您将发现错误

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();

  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

    });




  }
  rowappend($('tbody', '#tableInvoice'))

  function getValues(row) {

    const search = ($('[name=itemNametd]', row).val()).toString()
    console.log("search  : " + search)
    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);
    }

  }

  $(document).on('focusout', (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) {
    const row = event.target.parentElement.parentElement

    var keycode = event.keyCode || event.which;
    if (keycode == '13') {
      if (!$(event.target).val()) {
        e.preventDefault();
        return;
      }

      if (event.target.matches('[name=discPercentagetd]')) {

        if ($(row).parent().find('tr').length - $(row).index() === 1) {
          rowappend(event.target.parentElement.parentElement.parentElement)
        }
      }

    }


  });


}
<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">Item Code</th>
          <th id="unitQtyth" class="commanth">Unit Qty</th>
          <th id="purRateth" class="commanth">Pur.Rate</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" style="display: none;">
      <tfoot>


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

编辑/更新

当我按Enter键时,我已经编辑了代码段,如果它是Disc%输入字段,那么我正在创建新行,因此,当我更改dropdown(即供应商名称)时,它将使用上一个数据< / p>

假设我选择supplier 1,所以我正在输入(在输入字段中键入)并且tabledata在工作,但是当我选择supplier 2并输入数据时,第一行将得到{{1 }},但是当我输入并创建行时,nex行会显示供应商1的数据

2 个答案:

答案 0 :(得分:1)

您的问题在这一行:

import numpy as np
n = int(input())

values_encountered = np.zeros(n+1, dtype=bool)     # O(n)
values_encountered[[int(i) for i in input().split()]] = True # O(n)
# Or:
# values_encountered[list(map(int, input().split()))] = True

values_missing= (values_encountered == False) # O(n)
values_missing[0] = False
print(*list(*values_missing.nonzero())) # O(n)

数据变量继续具有第一个值。我建议简化代码。但是,如果没有机会,您可以将数据值另存为自动完成小部件的数据属性,并在需要时获取其值。

请查看.data()dataset了解详情。

您可以在创建自动完成时保存数据值:

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

您可以在以下日期获取值

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

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
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();

    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(function () {
            $("[name=itemNametd]", markup).last().focus()
        }, 100);

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

    rowappend($('tbody', '#tableInvoice'))

    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);
        }
    }

    $(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();
        }
    });

}

答案 1 :(得分:0)

问题$(document).on('focusout', (e) => {在这里,您正在文档上注册焦点事件。而是使用$('#itemNametd').on('focusout', (e) => {