HTML таблица не отображается правильно - PullRequest
0 голосов
/ 02 апреля 2019

У меня есть HTML-таблица с JSON DATA, я создаю один столбец в качестве поля ввода, мои заголовки таблиц: Code, Item Name, Unitcode, Quantity И AcceptedQty, в которых Я делаю поле ввода «Принятый объем», но поле «Количество» также преобразуется в поле ввода. Я не знаю, что я делаю неправильно

var tableDataDraft = [{
    "Code": "1326",
    "Item Name": "PINEAPPLE KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "3.00"
  },
  {
    "Code": "1494",
    "Item Name": "2D CAKE CHARGES PER KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "3.00"
  }
]


function addTableDraft(tableDataDraft) {
  var col = Object.keys(tableDataDraft[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    tr.appendChild(th);
    tr.classList.add("text-center");
    tr.classList.add("head")
  }
  for (var i = 0; i < tableDataDraft.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input"); //creating input field hidden
      hiddenField.style.display = "none";
      var tabledata = tableDataDraft[i][col[j]];
      if (tableDataDraft[i]['Code'] === tableDataDraft[i][col[j]]) { //now setting html attributes
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Name');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Unitcode'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Unit_code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Quantity'] === tableDataDraft[i][col[j]]) { //this quantity field i don't want to be input field

        hiddenField.setAttribute('name', 'Quantity');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['AcceptedQty'] === tableDataDraft[i][col[j]]) { //this one i want to be a input field

        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "AcceptedQty");
        quantityField.setAttribute("autocomplete", "on");
        quantityField.setAttribute("value", tabledata);
        quantityField.setAttribute("type", "tel");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        tabCell.appendChild(quantityField);
      }

      if (j > 1)
        tabCell.classList.add("text-right");
    }
  }
  var divContainer = document.getElementById("table");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");



}

addTableDraft(tableDataDraft)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="table-responsive" id="commonDvScroll">
  <table id=table></table>
</div>

почему это поле количества также отображается как поле ввода, я не знаю

Поскольку мой код немного длинен, потому что я добавляю форму HTML Attributes, потому что я хочу, чтобы все данные были на моем бэкэнде, поэтому я сериализую свою форму во время вызова ajax

Я прокомментировал все строки, где я делаю то, что вам всем будет легче понять

Ответы [ 2 ]

1 голос
/ 02 апреля 2019

Проблема заключается в том, что при вставке значений в строку вы сравниваете значения столбца вместо имени столбца . Это вызовет проблемы, когда значения одинаковы, например, Quantity и AcceptedQty имеют одинаковое значение 3.0. Попробуйте изменить один на 4.0, и вы можете заметить, что он работает.

Вот упрощенная версия вашего кода, которая проверяет, является ли текущий столбец AcceptedQty, и показывает поле ввода только для этого. У вас все еще могут быть другие блоки if, но убедитесь, что условие что-то вроде if (col[j] === 'Code') или (col[j] === 'Quantity') и т. Д.

var tableDataDraft = [{
    "Code": "1326",
    "Item Name": "PINEAPPLE KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "3.00"
  },
  {
    "Code": "1494",
    "Item Name": "2D CAKE CHARGES PER KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "3.00"
  }
]


function addTableDraft(tableDataDraft) {
  var col = Object.keys(tableDataDraft[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    tr.appendChild(th);
    tr.classList.add("text-center");
    tr.classList.add("head")
  }
  for (var i = 0; i < tableDataDraft.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input"); //creating input field hidden
      hiddenField.style.display = "none";
      var tabledata = tableDataDraft[i][col[j]];
      if (col[j] === 'AcceptedQty') { 
      //this one i want to be a input field
        
        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "AcceptedQty");
        quantityField.setAttribute("autocomplete", "on");
        quantityField.setAttribute("value", tabledata);
        quantityField.setAttribute("type", "tel");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        tabCell.appendChild(quantityField);
      }
      else
       { //now setting html attributes
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      
      if (j > 1)
        tabCell.classList.add("text-right");
    }
  }
  var divContainer = document.getElementById("table");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");



}

addTableDraft(tableDataDraft)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="table-responsive" id="commonDvScroll">
  <table id=table></table>
</div>
0 голосов
/ 02 апреля 2019

Изменить способ проверки возвращаемых данных. Вместо того, чтобы проверять, является ли значение тем же, проверьте ключ данных как это

if (col[j] === 'Quantity')

Затем вы можете вставить данные для этого конкретного столбца или ключа данных.

var tableDataDraft = [{
    "Code": "1326",
    "Item Name": "PINEAPPLE KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "7.00"
  },
  {
    "Code": "1494",
    "Item Name": "2D CAKE CHARGES PER KG",
    "Unitcode": "NOS",
    "Quantity": "3.00",
    "AcceptedQty": "10.00"
  }
]


function addTableDraft(tableDataDraft) {
  var col = Object.keys(tableDataDraft[0]);
  var countNum = col.filter(i => !isNaN(i)).length;
  var num = col.splice(0, countNum);
  col = col.concat(num);
  var table = document.createElement("table");
  var tr = table.insertRow(-1);
  for (var i = 0; i < col.length; i++) {
    var th = document.createElement("th");
    th.innerHTML = col[i];
    tr.appendChild(th);
    tr.classList.add("text-center");
    tr.classList.add("head")
  }
  for (var i = 0; i < tableDataDraft.length; i++) {
    tr = table.insertRow(-1);
    for (var j = 0; j < col.length; j++) {
      let tabCell = tr.insertCell(-1);
      var hiddenField = document.createElement("input"); //creating input field hidden
      hiddenField.style.display = "none";
      var tabledata = tableDataDraft[i][col[j]];
      if (tableDataDraft[i]['Code'] === tableDataDraft[i][col[j]]) { //now setting html attributes
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Item Name'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Item_Name');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (tableDataDraft[i]['Unitcode'] === tableDataDraft[i][col[j]]) {
        tabCell.innerHTML = tabledata;
        hiddenField.setAttribute('name', 'Unit_code');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
      }
      if (col[j] === 'Quantity') { //this quantity field i don't want to be input field
        var quantityNoEdit = document.createElement("input");
        quantityNoEdit.style.border = "none";
        quantityNoEdit.style["text-align"] = "right";
        quantityNoEdit.setAttribute("name", "Quantity");
        quantityNoEdit.setAttribute("autocomplete", "on");
        quantityNoEdit.setAttribute("value", tabledata);
        quantityNoEdit.setAttribute("type", "tel");
        quantityNoEdit.setAttribute("required", "required");
        quantityNoEdit.classList.add("dataReset");
        quantityNoEdit.toLocaleString('en-IN');
        quantityNoEdit.disabled = true;
        tabCell.appendChild(quantityNoEdit);
        hiddenField.setAttribute('name', 'Quantity');
        hiddenField.setAttribute('value', tabledata);
        tabCell.appendChild(hiddenField);
        console.log('Quantity:' + tableDataDraft[i][col[j]]);
      }
      if (tableDataDraft[i]['AcceptedQty'] === tableDataDraft[i][col[j]]) { //this one i want to be a input field

        var quantityField = document.createElement("input");
        quantityField.style.border = "none";
        quantityField.style["text-align"] = "right";
        quantityField.setAttribute("name", "AcceptedQty");
        quantityField.setAttribute("autocomplete", "on");
        quantityField.setAttribute("value", tabledata);
        quantityField.setAttribute("type", "tel");
        quantityField.setAttribute("required", "required");
        quantityField.classList.add("dataReset");
        quantityField.toLocaleString('en-IN');
        tabCell.appendChild(quantityField);
        console.log('AcceptedQty:' + col[j]);
      }

      if (j > 1)
        tabCell.classList.add("text-right");
    }
  }
  var divContainer = document.getElementById("table");
  divContainer.innerHTML = "";
  divContainer.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");



}

addTableDraft(tableDataDraft)
<table id="table"></table>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...