0

I have written some code that will allow a user to add rows to a table with a click of a button. In those rows input fields are inserted. My question is how do I make it so that the first column has the input type, "text" and so the middle columns have input type, "number". I would also like to have the last column not have an input field. Much appreciated! HTML:

<table id="table">
  <thead>
    <th id="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>
  </thead>
</table>

JavaScript:

function AddRow() {
   // Get ID for table from HTML file
   var table = document.getElementById("table");
   // Count number of columns in table
   var columnNumber = document.getElementById("table").rows[0].cells.length;
   // Add row to last row in table
   var row = document.getElementById("table").insertRow(-1);
   // Add columns to new row matching header
   for (i = 1; i <= columnNumber; i++) {
     // Create Input field in table
     var newInput = document.createElement("INPUT");
     newInput.placeholder = "Enter Text Here";
     newInput.classList.add("TableInput");
     row.insertCell(0).appendChild(newInput);
   }
 }

1 Answer 1

0

Continued from this

const tb = document.getElementById("tb");
const columnNumber = document.querySelectorAll("#table thead tr th").length - 2;
const inp = '<td><input type="number" placeholder="Raw Good Number" class="TableInput"/></td>';
let cnt = 1;
document.getElementById("add").addEventListener("click",() => {
  tb.innerHTML += `<tr>
    <td><input type="text" value="${cnt++}" /></td>
    ${[...Array(columnNumber).keys()].map(i => inp).join("")}
  </tr>`
})
input { width: 130px; }
<table id="table">
  <thead>
    <tr>
      <th id="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>
      <tbody id="tb">
      </tbody>
</table>

<p>Click button to test funtionality.</p>
<button type="button" id="add">Click Me</button>

Sign up to request clarification or add additional context in comments.

3 Comments

Does that JavaScript have to go in my, "AddRow" function or can it just sit in the file alone?
I can't get it to work, thank you for your help though.
@TaylorLarrechea My constact details are in my profile if you need me to look at your page

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.