1

function add_fields() {
  document.getElementById('myTable').innerHTML += '<tr> <td> <textarea name = "Product ID" placeholder = "Product ID"  style = "resize: none; width: 100%;"    document.getElementById("1")></textarea></td> <td> <textarea name = "Title" placeholder = "Title"   style = "resize: none; width: 100%;"></textarea></td><td> <textarea name = "startdate" placeholder = "startdate"   style = "resize: none; width: 100%;"></textarea></td> </tr>';
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<div class="set-form">
  <input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" />
</div>


<table id="myTable">
  product id : <input type="text" name="fname" id="1"><br>
  <thead>
    <tr>
      <th>Product ID</th>
      <th>Title</th>
      <th>Start Date</th>
      <th>End Date</th>
      <th>Excl</th>
      <th>Territory</th>
      <th>Media</th>
      <th>Language</th>
      <th>Format</th>
      <th>Acquiring Division</th>
      <th>Owner</th>

    </tr>
  </thead>
</table>

I want to add dynamically to the table by selecting the id whenever the user enters the data the data should add automatically to the table.

Is there any better way I want to add a column to the table and data to be added at once but I could not figure out so I planned the above code.

Any suggestions?

Ivan
  • 34,531
  • 8
  • 55
  • 100

3 Answers3

0

I find it easiest to just have a div/span which I write a table in dynamically with javascript, e.g.

example_array = [["Name","Age"],["Antonio","35"]];

function array_to_table(my_array){
  my_table_html = '<table>';
  for(var i = 0; i<my_array.length; i++){
    my_table_html += "<tr>";
    for(var j = 0; j < my_array[i].length; j++){
      my_table_html += "<td>"+my_array[i][j]+"</td>";
    }
    my_table_html += "</tr>";
  }
  my_table_html += '</table>';
  document.getElementById("mytable").innerHTML = my_table_html;
}

array_to_table(example_array);
<div id="mytable"></div>

When you have this framework for creating/updating tables, you can edit the array that's fed into the function to dynamically update your table.

  • It isn't recommended to use `innerHTML += `, read [this post](https://stackoverflow.com/questions/11515383/why-is-element-innerhtml-bad-code) for more information. – Ivan May 24 '18 at 14:16
0

Here is a working example, enter the desired values in the first row (I have only the first three elements here). Then click Add, the row will be added to the table.

function add_fields() {

  // select the input values
  let productId = document.querySelector('#productId').value
  let title = document.querySelector('#title').value
  let startDate = document.querySelector('#startDate').value

  // prepare a new row
  let tr = document.createElement('tr')
  tr.innerHTML = `
    <tr>
      <td>
        <div id="productId" style="resize: none; width: 100%;">${productId}</div>
      </td>
      <td>
        <div id="title" style="resize: none; width: 100%;">${title}</div>
      </td>
      <td>
        <div id="startDate" style="resize: none; width: 100%;">${startDate}</div>
      </td>
    </tr>
  `
  
  // remove content of textareas
  document.querySelector('#productId').value = ''
  document.querySelector('#title').value = ''
  document.querySelector('#startDate').value = ''
  
  // append a new row to the table
  document.querySelector('#myTable').appendChild(tr)

}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
<div class="set-form">
  <input type="button" id="more_fields" onclick="add_fields();" value="Add" class="btn btn-info" />
</div>
</head>

<body>
  <table id="myTable">
    <thead>
      <tr>
        <th>Product ID</th>
        <th>Title</th>
        <th>Start Date</th>
        <th>End Date</th>
        <th>Excl</th>
        <th>Territory</th>
        <th>Media</th>
        <th>Language</th>
        <th>Format</th>
        <th>Acquiring Division</th>
        <th>Owner</th>

      </tr>
      <tr>
        <td>
          <textarea id="productId" placeholder="Product ID" style="resize: none; width: 100%;"></textarea>
        </td>
        <td>
          <textarea id="title" placeholder="Title" style="resize: none; width: 100%;"></textarea></td>
        <td>
          <textarea id="startDate" placeholder="startdate" style="resize: none; width: 100%;"></textarea> </td>
      </tr>
    </thead>
  </table>

Here are a couple things you might want to know:

  • I'm using the method querySelector() from document to select an element from the DOM by its class or id. Don't forget to add the # to . before the actual name.
  • Access the value of an element of type textarea with its property value.
  • No use of innerHTML += as it will force the browser to re-render all the content of #myTable even if you're just adding a row. Best way is to prepare an element as I do and append it to the table with appendChild().
  • To easily write HTML inside JavaScript code, you can use backticks `` and insert JS variables directly in the markup with the ${} syntax.
Ivan
  • 34,531
  • 8
  • 55
  • 100
0

Playing a little with your code, I made the following modifications…

  • HTML stays in HTML, I've added a tr with id="row-type". It's hidden but the content is used to add a new tr when you click Add More. I've modified your existing function accordingly.
  • CSS stays in CSS, I've moved the table textarea style in the CSS.
  • As it's not recommended to use .innerHTML +=, I replaced it with .appendChild(…).
  • I've added a button in the row-type element. So that, when you click Submit, the content of the row is converted from textareas to texts.
  • As we're only adding in the 3 first tds, I've removed some of the other tds in the HTML to shorten the snippet. But it works exactly the same with all of it (I tried).
  • I've added a cancel function, in case you finally don't want to add.

…and ended-up with this working snippet:
(See comments in the code for more details)

// TAKIT: Now the content is in the HTML, append it to the current table
function add_fields() {
  // TAKIT: Replaced .innerHTML as it's not recommended
  var newElement = document.createElement('tr');
  newElement.innerHTML = document.getElementById('row-type').innerHTML;
  document.getElementById('myTable').appendChild(newElement);
}

// TAKIT: Added this function for when you click on the submit button
function put_in_table(elm) {
  var tds = elm.closest('tr').children; // Get all tds of the line you just clicked "submit"
  for (var i = 0; i < tds.length; i++) { // For all tds
    // replace the HTML with the text value of the textarea (that removes the textareas)
    if (tds[i].innerHTML)
      tds[i].innerText = tds[i].children[0].value || '';
  }
}

// TAKIT: Added this function to cancel the add
function cancel_add(elm) {
  elm.closest('tr').outerHTML = ''; // Empty current tr
}
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}


/* TAKIT: Added hidden on row type, and moved style of textareas here */

#row-type {
  display: none;
}

table textarea {
  resize: none;
  width: 100%;
}
<div class="set-form"><input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" /></div>
<table id="myTable">
  <!-- TAKIT: Added p element here, it's proper. What is it used for, by the way? -->
  <p>product id : <input type="text" name="fname" id="1"></p>
  <thead>
    <tr>
      <th>Product ID</th>
      <th>Title</th>
      <th>Start Date</th>
      <th>End Date</th>
      <th>Excl</th>
    </tr>
  </thead>
  <tbody>
    <!-- TAKIT: Added body and the "row-type" in it, so that HTML stays in HTML -->
    <tr id="row-type">
      <td><textarea name="Product ID" placeholder="Product ID"></textarea></td>
      <td><textarea name="Title" placeholder="Title"></textarea></td>
      <td><input name="startdate" type="date"></td>
      <td><input name="enddat" type="date"></td>
      <td>
        <button onclick="put_in_table(this);">Submit</button> <button onclick="cancel_add(this);">Cancel</button>
      </td>
    </tr>
  </tbody>
</table>

Hope it helps.

Takit Isy
  • 9,688
  • 3
  • 23
  • 47