Reputation: 47
I would like to create a input control inside a table row on every append. Basically like a shopping cart where I can add a quantity for every item in the table. I am struggling. I get [object HTMLInputElement] displayed when I do it as per below.
x.setAttribute("type", "text");
x.setAttribute("value", "Hello World!");
var create = document.body.appendChild(x);
let carttable = document.getElementById('cartlist');
let item = items[index];
let row = document.createElement('tr');
row.innerHTML = `
<td(${items.indexOf(item)})">${item.title}</td>
<td>${item.genre}</td>
<td>${"R" + item.price }</td>
<td>${x}</td> `;
carttable.append(row);
Upvotes: 0
Views: 1557
Reputation: 20944
You could either use the append
method to add your created input
to a td
and add that td
to the row
element.
let carttable = document.getElementById('cartlist');
let item = items[index];
let row = document.createElement('tr');
row.innerHTML = `
<td(${items.indexOf(item)})">${item.title}</td>
<td>${item.genre}</td>
<td>${"R" + item.price }</td>
`;
let cell = document.createElement('td');
let input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("value", "Hello World!");
cell.append(input);
row.append(cell);
carttable.append(row);
Or instead of creating your input with document.createElement
add it to your Template literal string in the row.innerHTML
.
let carttable = document.getElementById('cartlist');
let item = items[index];
let row = document.createElement('tr');
row.innerHTML = `
<td(${items.indexOf(item)})">${item.title}</td>
<td>${item.genre}</td>
<td>${"R" + item.price }</td>
<td><input type="text" value="Hello World!"></td>
`;
carttable.append(row);
Upvotes: 1
Reputation: 73906
You can use string directly for this purpose instead of document.createElement("input")
:
let carttable = document.getElementById('cartlist');
let item = items[index];
let row = document.createElement('tr');
row.innerHTML = `
<td (${items.indexOf(item)})">${item.title}</td>
<td>${item.genre}</td>
<td>${"R" + item.price }</td>
<td><input type="text" value="Hello World!" /></td>`;
carttable.append(row);
Upvotes: 0