У меня есть таблица HTML с данными JSON, я создаю один столбец в качестве поля ввода, заголовки моей таблицы 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.
Я прокомментировал все строки, где я что делаю, чтобы вам всем было легче понять
@designtocode, который я создал, чтобы показать AcceptedQty в качестве поля ввода, здесь я говорю о Quantity поле ввода
@dheerajkumar Это потому, что значение Quantity и AcceptedQty одинаково
@CarstenLøvboAndersen Я тоже так думаю, но проблема в том, что всегда одно и то же будет редактируемым, а другое непобедимым
@dheerajkumar проблема с этим разделом tableDataDraft[i]['AcceptedQty'] === tableDataDraft[i][col[j]]. Попробуйте изменить значение AcceptedQty на 4, и это сработает. Также добавьте table.innerHTML = tabledata для Quantity блока if.
@ raghav710, но проблема в том, что когда страница загружается изначально, оба столбца будут иметь одинаковые данные.
@dheerajkumar Я попытался объяснить свою точку зрения в своем ответе. Дайте мне знать, если это прояснит
@raghav710 позвольте мне проверить это один раз
@raghav710 привет, сэр, у меня есть небольшое сомнение
@dheerajkumar извините за задержку. Пожалуйста, спросите ваши сомнения
@ raghav710 это уже очищено, сэр



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Проблема в том, что при вставке значений в строку вы сравниваете значения столбца вместо имя столбца. Это вызовет проблемы, если значения совпадают, например, 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>здравствуйте, не могли бы вы проверить это один раз stackoverflow.com/questions/55846400/…
Измените способ проверки возвращаемых данных. Вместо того, чтобы проверять, совпадает ли значение, проверьте ключ данных следующим образом.
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.info('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.info('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>
«Почему это поле «Количество» также отображается как поле ввода, я не знаю», это из-за этого
var quantityField = document.createElement("input");