How to create a table dynamically according to data in an array

var arr=["1","2","-3","4","-5","-6","7"]  //  data changes as well arr[] size ;

      

There is a script here, this is done for me in the table dynamically. Table depends on arr[]

.

1) create one line <tr> <td></td></tr>,

where number <td> </td>

depends on lengtharr[];

2) Indicate style="background-color" to <td>

;

3) For negative numbers <td>

will be generated in index of that negative number

.

For example: here negative number indexes are 3,5,6.

 So for negative numbers in arr[]

create <td>

in the next line <tr><td></td></tr>

i.e. <td>

in 3,5,6 position

using background-color.

Here for -3,-5,-6

of, arr[]

create <td>

in first row <tr>

, but do not provide background-color

;

4) If there are no negative numbers in arr [], then do not create the second line;

Here the arr [] data changes, so the table must be dynamic.

For the above case, just a few codes to understand only

//length of arr = 7;

<tr>
<td style="background:#ccc">1</td>
<td style="background:#ccc">2</td>
<td style="background:#ccc"></td>
<td style="background:#ccc">4</td>
<td></td>
<td></td>
<td style="background:#ccc">7</td>
</tr>
<tr>
<td></td>
<td></td>
<td style="background:#ccc">-3</td>
<td></td>
<td style="background:#ccc">-5</td>
<td style="background:#ccc">-6</td>
<td></td>
</tr>

The above scenario will change according to data. Please help

      

+3


source to share


3 answers


var arr = ["1","2","-3","4","-5","-6","7"];

var table = document.createElement("table"),          // create the table element
    tbody = document.createElement("tbody");          // create the table body element
    
table.appendChild(tbody);                             // add the table body to table

// ### POSITIVE ROW ######################

var tr = document.createElement("tr");                // create the table row element
arr.forEach(function(e) {                             // for each element e in arr
  var td = document.createElement("td");              // create a table cell element
  if(e >= 0) {                                        // if e is positive
    td.textContent = e;                               // then change the text content of this cell to e
    td.style.background = "#ccc";                     // and change the background as well
  }
  tr.appendChild(td);                                 // add the cell to the row (if the number is negative the cell will be empty and without background)
});
tbody.appendChild(tr);                                // add the row to table


//### NEGATIVE ROW ######################

tr = document.createElement("tr");                    // same but for negative numbers ...
arr.forEach(function(e) {
  var td = document.createElement("td");
  if(e < 0) {
    td.textContent = e;
    td.style.background = "#ccc";
  }
  tr.appendChild(td);
});
tbody.appendChild(tr);

document.body.appendChild(table);
      

Run codeHide result


You can group a piece of code into a function and reuse it:



// elt is shortcut for document.createElement
function elt(tag) {
  return document.createElement(tag);
}

// take an array and a condition function conditionFN and return a row of all the element that passed the condition function with a background of #ccc
function makeRow(arr, conditionFN) {
  var tr = elt("tr");
  arr.forEach(function(e) {
    var td = elt("td");
    if (conditionFN(e)) {
      td.textContent = e;
      td.style.background = "#ccc";
    }
    tr.appendChild(td);
  });
  
  return tr;
}

// take an array and return the equivalent table element
function makeTable(arr) {
  var table = elt("table"),
      tbody = elt("tbody");

  table.appendChild(tbody);
  
  tbody.appendChild(makeRow(arr, function(e) { return e >= 0; })); // the condition function only allows positive numbers => positive row
  tbody.appendChild(makeRow(arr, function(e) { return e < 0; }));  // the condition function only allows negative numbers => negative row
  
  return table;
}



document.body.appendChild(makeTable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));
      

Run codeHide result


+2


source


Try this code:

var array=["1","2","-3","4","-5","-6","7"];

//creating table element---------
var table = document.createElement("table"),
tbody = document.createElement("tbody");

//append to table---------
table.appendChild(tbody);      
tbody.innerHTML=getTr(array);

//append to document---------
document.body.appendChild(table);


//console.log(getTr(arr));

//getting all tr---------
function getTr(arr,color='#ccc'){
  var ptd='',ntd ='';
  for(i=0;i<arr.length;i++){
     var std='<td style="background-color:'+color+';">';
     ptd += (arr[i]>=0)? std + arr[i]+'</td>':'<td></td>';
     ntd += (arr[i]<0)? std + arr[i]+'</td>':'<td></td>';
  }
  return '<tr>'+ptd+'</tr>'+'<tr>'+ntd+'</tr>';
}
      

Run codeHide result


You can see the simplification of the code result by using the function



//appending table to document------
document.body.appendChild(mktable([1, 2, -3, 4, -5, -6, -7, 8, 9, 10]));


//creating table element---------
function mktable(array){
    var table = document.createElement("table"),
    tbody = document.createElement("tbody");  
    tbody.innerHTML=getTr(array);
    table.appendChild(tbody);
    return table;
}


//getting all tr---------
function getTr(arr,color='#ccc'){
  var ptd='',ntd ='';
  for(i=0;i<arr.length;i++){
     var std='<td style="background-color:'+color+';">';
     ptd += (arr[i]>=0)? std + arr[i]+'</td>':'<td></td>';
     ntd += (arr[i]<0)? std + arr[i]+'</td>':'<td></td>';
  }
  return '<tr>'+ptd+'</tr>'+'<tr>'+ntd+'</tr>';
}
      

Run codeHide result


Note. It's simple and easy

0


source


Using a recursive function and table.inertRow()

androw.insertCell()

var data = ["1", "2", "-3", "4", "-5", "-6", "7"];
var table = document.getElementById('myTable')

function plusMinusRows(arr, rowNum) {      
  var row = table.insertRow();
  arr.map(Number).forEach(function(num) {
    var value = !rowNum  ? (num >= 0 ? num : '') : (num < 0 ? num : '');
    var cell = row.insertCell();
    cell.textContent = value;
    cell.style.background = value !== '' ? '#cccccc' : '';
  });
  // call function again when rowNum  not defined
  !rowNum && plusMinusRows(arr, 2);
}
// initialize 2 rows
plusMinusRows(data);
      

<table id="myTable"></table>
      

Run codeHide result


0


source







All Articles