#javascript #arrays #input #html-table #fill
#javascript #массивы #ввод #html-таблица #заполнить
Вопрос:
Ну, у меня есть таблица, состоящая из строк и столбцов, и один из этих столбцов состоит из всех текстовых полей, и если есть также массив, в котором есть значения, как эти значения могут быть размещены во всех текстовых полях для этого столбца по порядку?
const row = document.querySelectorAll("tr");
let numberOfColumns;
const marks = [2, 5, 7, 6, 4, 9]
row.forEach(( item ) => {
const columnsOfInput = item.querySelectorAll(["td > input"]);
numberOfColumns = columnsOfInput.length
for (let i = 0; i < columnsOfInput.length; i ) {
for (let mark in marks) {
columnsOfInput[ 0 ].value = mark.slice()
/*
All fields will be filled with number 5, meaning the array length, but this is not the goal!
How to place all values of "marks" array to all fields in order 2, 5, 7, 6, 4, 9 ?
*/
}
}
});
console.log(`number of columns: ${numberOfColumns}`); // all columns that has text fields
<body>
<table style="width:50%; text-align: center">
<tr>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td></td>
</tr>
</table>
</body>
Ответ №1:
Вы можете попробовать сделать что-то похожее на это:
const row = document.querySelectorAll("tr");
let numberOfColumns, marksIndex = -1;
const marks = [2, 5, 7, 6, 4, 9]
row.forEach(( item) => {
const columnsOfInput = item.querySelectorAll(["td > input"]);
numberOfColumns = columnsOfInput.length;
for (let i = 0; i < columnsOfInput.length; i ) {
for(let mark in marks){
columnsOfInput[i].value = marks[marksIndex];
}
}
marksIndex ;
});
Это должно дать вам 5 строк, которые вы закодировали в своем HTML, и иметь значение 2 в Mark1 и Mark2, затем 5 в Mark1 и Mark2 и т.д…
Если это не то, что вы собирались, дайте мне знать, и я постараюсь помочь снова.