Create html table from comma separated strings javascript

12,270

Solution 1

Something like this:

var schoolArr = school_list.split(',');
var pctArr = pct_list.split(',');
var table = "<table>";
for (var i=0; i< schoolArr.length; i++) {
    table = table + "<tr><td>"+ schoolArr[i]+"</td><td>"+ pctArr[i] +"</td></tr>"; 
}
table = table + "</table>";

return table;

Solution 2

You can try below code with Jsfiddle demo ::

function createTable(tab) {
  var tar = document.getElementById(tab);
  var table = document.createElement('TABLE');
  table.border = '1';
  var tbdy = document.createElement('TBODY');
  table.appendChild(tbdy);
  for (var j = 0; j < 4; j++) {
    var tr = document.createElement('TR');
    tbdy.appendChild(tr);
    for (var k = 0; k < 2; k++) {
      var td = document.createElement('TD');
      td.width = '100';
      if (k == 0) td.innerHTML = "School" + (j + 1);
      else td.innerHTML = "Percent" + (j + 1);
      tr.appendChild(td);
    }
  }
  tar.appendChild(table);
}

createTable('tab');
<div id="tab"></div>
Share:
12,270
mike
Author by

mike

Updated on June 16, 2022

Comments

  • mike
    mike almost 2 years

    I am trying to write a Javascript function which writes the text to (eventually) create the following html tables (I will be passing different length arguments to it to create hundreds of tables):

    <table>
        <tr><td><u>School</u></td>
        <td><u>Percent</u></td>
        <tr><td>School 1: </td>
        <td>Percent1</td></tr>
        <tr><td>School 2: </td>
        <td>Percent2</td></tr>
        <tr><td>School 3: </td>
        <td>Percent3</td></tr>  
    </table>
    

    The inputs that I have are comma separated strings:

    var school_list = "School 1, School 2, School 3"
    var pct_list = "Percent1, Percent2, Percent3"
    

    The function needs to be passed school_list and pct_list, and return a string of the html table code above.