简体   繁体   中英

How do I dynamically add an input field into a cell inside my html table row in javascript?

This is my code:

var tab=document.getElementById("quarter_details");
var input = document.createElement("input");
input.type = "text";
input.placeholder = "dd/mm/yyyy";
input.id = "vac";

var row = tab.insertRow(5);
var cell = row.insertCell(0);
var cell1 = row.insertCell(1);

cell.innerHTML = "<b>Date:</b>";
cell1.innerHTML = input; //[object HTMLInputElement]

When I run the code, the input text field doesn't appear. What do I do?

EDIT: Tried using cell1.appendChild = input . Now it shows an empty cell, with no input field

使用appendChild方法:

cell1.appendChild(input);

Use insertAdjacentHTML . Here's a minimal reproducable example .

 const createDateTimeInput = (forCell, id) => { forCell.textContent = ``; // empty the cell forCell.insertAdjacentHTML( `beforeend`, `<b>Date</b> <input type="text" placeholder="dd/mm/yyyy" id="${id}">`); }; const firstCellOfSecondRow = document.querySelector(`table tbody tr:nth-child(2) > td`); setTimeout(() => createDateTimeInput(firstCellOfSecondRow, `vac`), 2000);
 thead th { text-align: left }
 <table> <thead> <tr> <th>first column</th> <th>second column</th> </tr> </thead> <tbody> <tr> <td>cell</td> <td>cell</td> </tr> <tr> <td>cell</td> <td>cell</td> </tr> </tbody> </table>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM