Reputation: 53
I looped through an object to transfer its elements to an HTML table. The table has 4 columns. 2 of those columns is a number text box. The string from the object should be transferred to those number text box. One of those were successfully transferred, the one on the amount column, but the one on the calorie column does not show up. I'm looking for ways for the designated calorie numbers from the object to be transferred to the number text box on the HTML Table.
let mealObj = {
menu1: {
menuName: "Steak",
ingr1: {
name: "Butter",
ingrType: "other",
amount: "2",
amountType: "tbsp",
cal: "10",
},
ingr2: {
name: "Parsley",
ingrType: "vegetable",
amount: "1",
amountType: "tsp",
cal: "1",
},
ingr3: {
name: "Garlic",
ingrType: "vegetable",
amount: "1/2",
amountType: "tsp",
cal: "20",
},
ingr4: {
name: "Soy Sauce",
ingrType: "other",
amount: "1/4",
amountType: "tsp",
cal: "20",
},
ingr5: {
name: "Beef",
ingrType: "meat",
amount: "3/4",
amountType: "lbs",
cal: "200",
},
ingr6: {
name: "Salt",
ingrType: "other",
amount: "1/8",
amountType: "tsp",
cal: "0",
},
ingr7: {
name: "Pepper",
ingrType: "other",
amount: "1/8",
amountType: "tsp",
cal: "2",
},
},
}
let ingrTable = document.getElementById("ingr-table");
objToTable(mealObj);
function objToTable(ingrList) {
let totalRowLength = ingrTable.rows.length;
for (let i in ingrList) {
for (let k in ingrList[i]) {
if (ingrList[i][k].name !== undefined) {
let tableAmount = document.createElement("INPUT");
tableAmount.setAttribute("type", "number");
tableAmount.id = "table-amount";
let tableCalNum = document.createElement("INPUT");
tableCalNum.setAttribute("type", "number");
tableCalNum.id = "table-cal";
let row = ingrTable.insertRow(totalRowLength);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);
cell1.innerHTML = ingrList[i][k].name;
cell2.appendChild(tableAmount);
tableAmount.value = eval(ingrList[i][k].amount);
cell3.innerHTML = ingrList[i][k].amountType;
cell4.appendChild(tableCalNum);
tableCalNum = ingrList[i][k].cal;
}
}
}
}
<table id="ingr-table">
<tr>
<th>Ingredient</th>
<th colspan="2">Amount</th>
<th>Calorie</th>
<th></th>
</tr>
</table>
Upvotes: 1
Views: 37
Reputation: 161
tableCalNum.value = ingrList[i][k].cal;
Set the tableCalNum by using .value
Upvotes: 1