Skip to content Skip to sidebar Skip to footer

Add Input To Each Column Of Html Table

I am trying to add an input field to each cell of my HTML table when I add a new row. The problem is that each time I click the button it only adds an input field to the first colu

Solution 1:

Clone the input or simplify the script

I made the HTML valid and use an eventListener as recommended

const tb = document.getElementById("tb");
const columnNumber = document.querySelectorAll("#table thead tr th").length - 1;
const inp = '<td><input type="text" placeholder="Raw Good Name" class="TableInput"/></td>';
let cnt = 1;
document.getElementById("add").addEventListener("click",() => {
  tb.innerHTML += `<tr>
    <td class="right">${cnt++}</td>
    ${[...Array(columnNumber).keys()].map(i => inp).join("")}
  </tr>`
})
.right {
  text-align: right;
}
<tableid="table"><thead><tr><thid="item">Item</th><th>Ounces (Oz)</th><th>Grams (g)</th><th>Fluid Ounces (FOz)</th><th>Milliliters (mL)</th><th>Drops</th><th>Completed</th></tr><thead><tbodyid="tb"></tbody></table><p>Click button to test funtionality.</p><buttontype="button"id="add">Click Me</button>

Solution 2:

You need to be creating the input and appending it to the cell within the loop that creates the cells so that more than one will be created.

/* This is only here for display purposes in the Stack Overflow environment */input { width:5em; }
<tableid="table"><tr><thid="item">Item</th><th>Ounces (Oz)</th><th>Grams (g)</th><th>Fluid Ounces (FOz)</th><th>Milliliters (mL)</th><th>Drops</th><th>Completed</th></tr></table><p>Click button to test funtionality.</p><buttononclick="AddRow()">Click Me</button><script>functionAddRow() {
   // Get ID for table from HTML filevar table = document.getElementById("table");
   // Count number of columns in tablevar columnNumber = document.getElementById("table").rows[0].cells.length;
   // Add row to last row in tablevar row = document.getElementById("table").insertRow(-1);

   // Add columns to new row matching header// Loop should start at 0 and continue as long as you are less than// the array lengthfor (i = 0; i < columnNumber; i++) {
     // Create Input field in tablevar newInput = document.createElement("INPUT");
     // newInput.setAttribute("type", "text"); <-- Not needed: type="text" is the default// newInput.setAttribute("placeholder", "Raw Good Name"); <-- See following line for simpler syntax
     newInput.placeholder = "Raw Good Name";
     newInput.classList.add("TableInput");
     
     // If we're not on the first of last columnif(i !== 0 && i < columnNumber - 1){
       newInput.type = "number"; // Make the input a number
     }
     
     row.insertCell(0).appendChild(newInput);
   }
 }
</script>

Post a Comment for "Add Input To Each Column Of Html Table"