最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Append to HTML Table using Javascript with Data-elements - Stack Overflow

programmeradmin1浏览0评论

I have four arrays

arrayOne['orange','blue','green','red','yellow','purple','gray','tan','pink','violet']
arrayTwo['1001','1003','3453','78934','2389','3','8934']
arrayThree['TV','phone','laptop']
arrayFour['1','2','3','4','5','6','7','8','9','10']

I am making a table in html

<table class="table table-striped">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
   </tr>
</thead>

I have a script that opens a modal and appends to the table I have tried to get it working for two columns but it is only populating the first column with ArrayOne contents

for (row = 0; row <$(this).data("arrayOne").length; row++ ){
  $("#myModal").find(".table").append("<tr>
  <td>"+$(this).data("arrayOne")[row]+"</td>"); 

  for (j = 0; j <$(this).data("arrayTwo").length; j++ ){
    $("#myModal").find(".table").append("<tr>
    <td>"+$(this).data("arrayTwo")[j]+"</td></tr></tbody></table>");
  } 
} 

With the code above it only prints out as

column1    column2    column 3    column 4
orange
blue
green
red
....
violet

The end result should look something like this

column1    column2    column 3    column 4
orange     1001       TV          1
blue       1003       phone       2
green      3453       laptop      3
red        78934                  4
yellow     2389                   5

Etc, Etc

I have four arrays

arrayOne['orange','blue','green','red','yellow','purple','gray','tan','pink','violet']
arrayTwo['1001','1003','3453','78934','2389','3','8934']
arrayThree['TV','phone','laptop']
arrayFour['1','2','3','4','5','6','7','8','9','10']

I am making a table in html

<table class="table table-striped">
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
      <th>Column 3</th>
      <th>Column 4</th>
   </tr>
</thead>

I have a script that opens a modal and appends to the table I have tried to get it working for two columns but it is only populating the first column with ArrayOne contents

for (row = 0; row <$(this).data("arrayOne").length; row++ ){
  $("#myModal").find(".table").append("<tr>
  <td>"+$(this).data("arrayOne")[row]+"</td>"); 

  for (j = 0; j <$(this).data("arrayTwo").length; j++ ){
    $("#myModal").find(".table").append("<tr>
    <td>"+$(this).data("arrayTwo")[j]+"</td></tr></tbody></table>");
  } 
} 

With the code above it only prints out as

column1    column2    column 3    column 4
orange
blue
green
red
....
violet

The end result should look something like this

column1    column2    column 3    column 4
orange     1001       TV          1
blue       1003       phone       2
green      3453       laptop      3
red        78934                  4
yellow     2389                   5

Etc, Etc

Share Improve this question edited Aug 1, 2017 at 15:07 Colin 1,1421 gold badge16 silver badges28 bronze badges asked Aug 1, 2017 at 13:53 jumpman8947jumpman8947 5911 gold badge14 silver badges37 bronze badges 1
  • you should try to close your <tr> before opening a new one.. EDIT: one of your problems is also that by appending raw html code, you should fill rows with all of your 4 arrays at once, because a <tr> is the horizontal part of that table – Kaddath Commented Aug 1, 2017 at 13:57
Add a ment  | 

7 Answers 7

Reset to default 2

Assuming arrayOne has all the required rows, and on other arrays the rows may be blank, you can do something like,

 arrayOne.forEach(function(value, key){
     let firstColumn = arrayOne[key],
         secondColumn = arrayTwo[key]?arrayTwo[key]:"",
         thirdColumn = arrayThree[key]?arrayThree[key]:"",
         fourthColumn = arrayFour[key]?arrayFour[key]:"";

     $("#myModal").find(".table").append('<tr><td>'+firstColumn+'</td><td>'+secondColumn+'</td><td>'+thirdColumn+'</td><td>'+fourthColumn+'</td></tr>');
 });

A jQuery solution to fill the table body can be:

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];
for (var i = 0; i <arrayOne.length; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="table table-striped">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

Here you go with a solution https://jsfiddle/phru3m7s/1/

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];


for(var i=0; i< arrayOne.length; i++){
	var tableString = "<tr>";
  	tableString += "<td>" + arrayOne[i] + "</td>";
    tableString += "<td>" + ((typeof arrayTwo[i] === 'undefined') ? '' : arrayTwo[i]) + "</td>";
    tableString += "<td>" + ((typeof arrayThree[i] === 'undefined') ? '' : arrayThree[i])  + "</td>";
    tableString += "<td>" + ((typeof arrayFour[i] === 'undefined') ? '' : arrayFour[i]) + "</td>";
  tableString += "<tr>";
  
  $('table tbody').append(tableString);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
  <thead>
      <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
      </tr>
  </thead>
  <tbody>
  </tbody>
</table>

var arrayOne = ['orange','blue','green','red','yellow','purple','gray','tan','pink','violet'];
var arrayTwo = ['1001','1003','3453','78934','2389','3','8934'];
var arrayThree = ['TV','phone','laptop'];
var arrayFour = ['1','2','3','4','5','6','7','8','9','10'];

//To test the longest array
var length_array = [];
length_array.push( arrayOne.length); 
length_array.push( arrayTwo.length); 
length_array.push( arrayThree.length); 
length_array.push( arrayFour.length); 

var maxLength = Math.max.apply( null, length_array );

for (var i = 0; i <maxLength; i++ ){
    var row = $('<tr/>').append($('<td/>', {text: arrayOne[i] || ''}))
            .append($('<td/>', {text: arrayTwo[i] || ''}))
            .append($('<td/>', {text: arrayThree[i] || ''}))
            .append($('<td/>', {text: arrayFour[i] || ''}));
    $('table tbody').append(row);
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table class="table table-striped">
    <thead>
    <tr>
        <th>Column 1</th>
        <th>Column 2</th>
        <th>Column 3</th>
        <th>Column 4</th>
    </tr>
    </thead>
    <tbody>
    </tbody>
</table>

You can try this

for (row = 0; row <$(this).data("arrayOne").length; row++ )
{
    var valOne = ($(this).data("arrayOne")[row]!=null)?$(this).data("arrayOne")[row]:"";
    var valTwo = ($(this).data("arrayTwo")[row]!=null)?$(this).data("arrayTwo")[row]:"";
    var valThree = ($(this).data("arrayThree")[row]!=null)?$(this).data("arrayThree")[row]:"";
    var valFour = ($(this).data("arrayFour")[row]!=null)?$(this).data("arrayFour")[row]:"";

    $("#myModal").find(".table").append("<tr><td>"+valOne+"</td><td>"+valTwo+"</td><td>"+valThree+"</td><td>"+valFour+"</td></tr>");
} 

Approach to bine your individual arrays into one array and determine which is the longest then loop over that to generate the rows

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'],
  arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'],
  arrayThree = ['TV', 'phone', 'laptop'],
  arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];

var columns = [arrayOne, arrayTwo, arrayThree, arrayFour];
// start from longest column array
var rows = columns.reduce((a, c) => {
    return c.length > a.length ? c : a;
  }, [])
  // map the longest to create all the rows
  .map((_, rowIdx) => {
    // map the cells for each row
    var cells = columns.map(colArr => $('<td>',{text: colArr[rowIdx] || '' }));
    // return new row and cells
    return $('<tr>').append(cells);    
  });
 
// append all the rows     
$('#myModal tbody').append(rows);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
  <table>
     <thead>
        <tr>
          <th>Column 1</th>
          <th>Column 2</th>
          <th>Column 3</th>
          <th>Column 4</th>
       </tr>
    </thead>
    <tbody></tbody>
  </table>
</div>

There is a modern and reasonably elegant way to do this using Array.prototype.reduce(), as you can see in the example below:

var arrayOne = ['orange', 'blue', 'green', 'red', 'yellow', 'purple', 'gray', 'tan', 'pink', 'violet'];
var arrayTwo = ['1001', '1003', '3453', '78934', '2389', '3', '8934'];
var arrayThree = ['TV', 'phone', 'laptop'];
var arrayFour = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10'];
var sumArray = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}];
var mergedArrays = [arrayOne, arrayTwo, arrayThree, arrayFour].reduce(function(sum, value, index) {
  for (var key in sum) {
    sum[key][index] = value[key];
  }
  return sum;
}, sumArray);

console.log(mergedArrays);

var htmlToRender = '<table class="table table-striped"><thead><tr><th>Column 1</th><th>Column 2</th><th>Column 3</th><th>Column 4</th></tr></thead><tbody>';

for (var key in mergedArrays) {
  htmlToRender += '<tr><td>' + mergedArrays[key][0] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][1] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][2] + '</td>';
  htmlToRender += '<td>' + mergedArrays[key][3] + '</td></tr>';
}

htmlToRender += '</tbody></table>';
$("#myModal").append(htmlToRender);
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myModal">
</div>

Explanation

You essentially create an empty array of objects and then you accumulate the values of your existing arrays as objects with 4 values. After this is all done, you can iterate over the array of objects and write a new row in the table for each object in the array.

The code can be easily expanded and tweaked for more plex cases. Also, the length of the sumArray can be variable and tweaked based on your needs.

Also, as pointed out in this answer's ments, appending closing tags is a really bad practice, so the above code uses a better one, rendering the whole table instead of only its contents and the closing tags.

发布评论

评论列表(0)

  1. 暂无评论