0

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);
1
  • 1
    because you are building a string and contacting a string and an object. Either you have to build the input as a string or build your table row as DOM objects. Commented Feb 24, 2020 at 14:30

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.