Eric.18 Eric.18 - 1 month ago 6
HTML Question

HTML table from multiple JavaScript arrays

I am building a little interactive website for some people to use. I have a lot of it built but am stuck on this part.

There are 4 arrays that are based on a users selections, they start as empty arrays. As a user clicks on an item it's four components are added to each array respectively, they are all numbers.

Item 1: 3,5,7,9

Item 2: 2,4,6,8

var bgArray = [3,2];
var minority = [5,4];
var poverty = [7,6];
var lep = [9,8];


What I want to do is build an HTML table from the four arrays and have it look like the following. Basically row 1 would be [0] for each array, row 2 would be [1] and so on. I cannot figure out a way to get them to line up. (run code snippet to see table)



<table>
<tr>
<td>H1</td>
<td>H2</td>
<td>H3</td>
<td>H4</td>

</tr>
<tr>
<td>3</td>
<td>5</td>
<td>7</td>
<td>9</td>

</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
<td>8</td>
</tr>
</table>





I plan to have users make their selections and then click a button to generate the table. They can also deselect an item and regenerate the table.

Thanks in advance.

Answer

Eric, this code may be what you are requesting. This will help you draw your table with the values of the arrays on a button click.

var bgArray = [3,2,1]; 
var minority = [5,4,3];
var poverty = [7,6,5];
var lep = [9,8,7];

$("button").on("click", function(e){
  e.preventDefault();
  
  // Get the length of one array
  var numRows = bgArray.length;
  
  // Clear the table (except first row)
  $("table tr:not(:first-child)").remove();
  
  // Add the rows
  for(var i = 0; i < numRows; i++){
    var newRow = $("<tr></tr>");
    newRow.append(createNewColData(bgArray[i]));
    newRow.append(createNewColData(minority[i]));
    newRow.append(createNewColData(poverty[i]));
    newRow.append(createNewColData(lep[i]));
    $("table").append(newRow);
  }  
});

// Auxiliar function to render a table data
function createNewColData(data){
  return "<td>" + data + "</td>";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Add values</button>
<br/>
<br/>
<table>
  <tr>
    <td>H1</td>
    <td>H2</td>
    <td>H3</td>
    <td>H4</td>
  </tr>
</table>

I'm not sure how your button display will work, but if you update your markup I could update my answer.

Good luck and happy coding!

Comments