[javascript] Create table with jQuery - append

I have on page div:

<div id="here_table"></div>

and in jquery:

for(i=0;i<3;i++){
    $('#here_table').append( 'result' +  i );
}

this generating for me:

<div id="here_table">
    result1 result2 result3 etc
</div>

I would like receive this in table:

<div id="here_table">
    <table>
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
    </table>
</div>

I doing:

$('#here_table').append(  '<table>' );

 for(i=0;i<3;i++){
    $('#here_table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

 $('#here_table').append(  '</table>' );

but this generate for me:

<div id="here_table">
    <table> </table> !!!!!!!!!!
          <tr><td>result1</td></tr>
          <tr><td>result2</td></tr>
          <tr><td>result3</td></tr>
</div>

Why? how can i make this correctly?

LIVE: http://jsfiddle.net/n7cyE/

This question is related to javascript jquery html

The answer is


Or static HTML without the loop for creating some links (or whatever). Place the <div id="menu"> on any page to reproduce the HTML.

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>HTML Masterpage</title>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

        <script type="text/javascript">
            function nav() {
                var menuHTML= '<ul><li><a href="#">link 1</a></li></ul><ul><li><a href="#">link 2</a></li></ul>';
                $('#menu').append(menuHTML);
            }
        </script>

        <style type="text/css">
        </style>
    </head>
    <body onload="nav()">
        <div id="menu"></div>
    </body>
    </html>

It is important to note that you could use Emmet to achieve the same result. First, check what Emmet can do for you at https://emmet.io/

In a nutshell, with Emmet, you can expand a string into a complexe HTML markup as shown in the examples below:

Example #1

ul>li*5

... will produce

<ul>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

Example #2

div#header+div.page+div#footer.class1.class2.class3

... will produce

<div id="header"></div>
<div class="page"></div>
<div id="footer" class="class1 class2 class3"></div>

And list goes on. There are more examples at https://docs.emmet.io/abbreviations/syntax/

And there is a library for doing that using jQuery. It's called Emmet.js and available at https://github.com/christiansandor/Emmet.js


You need to append the tr inside the table so I updated your selector inside your loop and removed the closing table because it is not necessary.

$('#here_table').append(  '<table />' );

 for(i=0;i<3;i++){
    $('#here_table table').append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

The main problem was that you were appending the tr to the div here_table.

Edit: Here is a JavaScript version if performance is a concern. Using document fragment will not cause a reflow for every iteration of the loop

var doc = document;

var fragment = doc.createDocumentFragment();

for (i = 0; i < 3; i++) {
    var tr = doc.createElement("tr");

    var td = doc.createElement("td");
    td.innerHTML = "content";

    tr.appendChild(td);

    //does not trigger reflow
    fragment.appendChild(tr);
}

var table = doc.createElement("table");

table.appendChild(fragment);

doc.getElementById("here_table").appendChild(table);

I wrote rather good function that can generate vertical and horizontal tables:

function generateTable(rowsData, titles, type, _class) {
    var $table = $("<table>").addClass(_class);
    var $tbody = $("<tbody>").appendTo($table);


    if (type == 2) {//vertical table
        if (rowsData.length !== titles.length) {
            console.error('rows and data rows count doesent match');
            return false;
        }
        titles.forEach(function (title, index) {
            var $tr = $("<tr>");
            $("<th>").html(title).appendTo($tr);
            var rows = rowsData[index];
            rows.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });

    } else if (type == 1) {//horsantal table 
        var valid = true;
        rowsData.forEach(function (row) {
            if (!row) {
                valid = false;
                return;
            }

            if (row.length !== titles.length) {
                valid = false;
                return;
            }
        });

        if (!valid) {
            console.error('rows and data rows count doesent match');
            return false;
        }

        var $tr = $("<tr>");
        titles.forEach(function (title, index) {
            $("<th>").html(title).appendTo($tr);
        });
        $tr.appendTo($tbody);

        rowsData.forEach(function (row, index) {
            var $tr = $("<tr>");
            row.forEach(function (html) {
                $("<td>").html(html).appendTo($tr);
            });
            $tr.appendTo($tbody);
        });
    }

    return $table;
}

usage example:

var title = [
    '????? ?????',
    '????? ?????????',
    '????? ?? ???'
];

var rows = [
    [number_format(data.source.area,2)],
    [number_format(data.intersection.area,2)],
    [number_format(data.deference.area,2)]
];

var $ft = generateTable(rows, title, 2,"table table-striped table-hover table-bordered");

$ft.appendTo( GroupAnalyse.$results );

var title = [
    '???',
    '?????? ????',
    '?????? ????',
    '?????',
    '????? ??? ?????',
];

var rows = data.edgesData.map(function (r) {
    return [
        r.directionText,
        r.lineLength,
        r.newLineLength,
        r.stateText,
        r.lineLengthDifference
    ];
});


var $et = generateTable(rows, title, 1,"table table-striped table-hover table-bordered");

$et.appendTo( GroupAnalyse.$results );

$('<hr/>').appendTo( GroupAnalyse.$results );

example result:

example result


As for me, this approach is prettier:

String.prototype.embraceWith = function(tag) {
    return "<" + tag + ">" + this + "</" + tag + ">";
};

var results = [
  {type:"Fiat", model:500, color:"white"}, 
  {type:"Mercedes", model: "Benz", color:"black"},
  {type:"BMV", model: "X6", color:"black"}
];

var tableHeader = ("Type".embraceWith("th") + "Model".embraceWith("th") + "Color".embraceWith("th")).embraceWith("tr");
var tableBody = results.map(function(item) {
    return (item.type.embraceWith("td") + item.model.toString().embraceWith("td") + item.color.embraceWith("td")).embraceWith("tr")
}).join("");

var table = (tableHeader + tableBody).embraceWith("table");

$("#result-holder").append(table);

A working example using the method mentioned above and using JSON to represent the data. This is used in my project of dealing with ajax calls fetching data from server.

http://jsfiddle.net/vinocui/22mX6/1/

In your html: < table id='here_table' >< /table >

JS code:

function feed_table(tableobj){
    // data is a JSON object with
    //{'id': 'table id',
    // 'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}], 
    // 'data': [{'a': 'Non Real Estate',  'b' :'Credit card',  'c' :'$5000' , 'd': 'Edit/Delete' },...   ]}

    $('#' + tableobj.id).html( '' );

    $.each([tableobj.header, tableobj.data], function(_index, _obj){
    $.each(_obj, function(index, row){
        var line = "";
        $.each(row, function(key, value){
            if(0 === _index){
                line += '<th>' + value + '</th>';    
            }else{
                line += '<td>' + value + '</td>';
            }
        });
        line = '<tr>' + line + '</tr>';
        $('#' + tableobj.id).append(line);
    });


    });    
}

// testing
$(function(){
    var t = {
    'id': 'here_table',
    'header':[{'a': 'Asset Tpe', 'b' : 'Description', 'c' : 'Assets Value', 'd':'Action'}], 
    'data': [{'a': 'Non Real Estate',  'b' :'Credit card',  'c' :'$5000' , 'd': 'Edit/Delete' },
         {'a': 'Real Estate',  'b' :'Property',  'c' :'$500000' , 'd': 'Edit/Delete' }
        ]};

    feed_table(t);
});

When you use append, jQuery expects it to be well-formed HTML (plain text counts). append is not like doing +=.

You need to make the table first, then append it.

var $table = $('<table/>');
for(var i=0; i<3; i++){
    $table.append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}
$('#here_table').append($table);

To add multiple columns and rows, we can also do a string concatenation. Not the best way, but it sure works.

             var resultstring='<table>';
      for(var j=0;j<arr.length;j++){
              //array arr contains the field names in this case
          resultstring+= '<th>'+ arr[j] + '</th>';
      }
      $(resultset).each(function(i, result) {
          // resultset is in json format
          resultstring+='<tr>';
          for(var j=0;j<arr.length;j++){
              resultstring+='<td>'+ result[arr[j]]+ '</td>';
          }
          resultstring+='</tr>';
      });
      resultstring+='</table>';
          $('#resultdisplay').html(resultstring);

This also allows you to add rows and columns to the table dynamically, without hardcoding the fieldnames.



i prefer the most readable and extensible way using jquery.
Also, you can build fully dynamic content on the fly.
Since jquery version 1.4 you can pass attributes to elements which is,
imho, a killer feature. Also the code can be kept cleaner.

$(function(){

        var tablerows = new Array();

        $.each(['result1', 'result2', 'result3'], function( index, value ) {
            tablerows.push('<tr><td>' + value + '</td></tr>');
        });

        var table =  $('<table/>', {
           html:  tablerows
       });

        var div = $('<div/>', {
            id: 'here_table',
            html: table
        });

        $('body').append(div);

    });

Addon: passing more than one "html" tag you've to use array notation like: e.g.

var div = $('<div/>', {
            id: 'here_table',
            html: [ div1, div2, table ]
        });

best Rgds.
Franz


<table id="game_table" border="1">

and Jquery

var i;
for (i = 0; ii < 10; i++) 
{

        var tr = $("<tr></tr>")
        var ii;
        for (ii = 0; ii < 10; ii++) 
        {
        tr.append(`<th>Firstname</th>`)
        }

$('#game_table').append(tr)
}

Or do it this way to use ALL jQuery. The each can loop through any data be it DOM elements or an array/object.

var data = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight'];
var numCols = 1;           


$.each(data, function(i) {
  if(!(i%numCols)) tRow = $('<tr>');

  tCell = $('<td>').html(data[i]);

  $('table').append(tRow.append(tCell));
});
?

http://jsfiddle.net/n7cyE/93/


Following is done for multiple file uploads using jquery:

File input button:

<div>
 <input type="file" name="uploadFiles" id="uploadFiles" multiple="multiple" class="input-xlarge" onchange="getFileSizeandName(this);"/> 
</div>

Displaying File name and File size in a table:

<div id="uploadMultipleFilediv">
<table id="uploadTable" class="table table-striped table-bordered table-condensed"></table></div>

Javascript for getting the file name and file size:

function getFileSizeandName(input)
{
    var select = $('#uploadTable');
    //select.empty();
    var totalsizeOfUploadFiles = "";
    for(var i =0; i<input.files.length; i++)
    {
        var filesizeInBytes = input.files[i].size; // file size in bytes
        var filesizeInMB = (filesizeInBytes / (1024*1024)).toFixed(2); // convert the file size from bytes to mb
        var filename = input.files[i].name;
        select.append($('<tr><td>'+filename+'</td><td>'+filesizeInMB+'</td></tr>'));
        totalsizeOfUploadFiles = totalsizeOfUploadFiles+filesizeInMB;
        //alert("File name is : "+filename+" || size : "+filesizeInMB+" MB || size : "+filesizeInBytes+" Bytes");               
    }           
}

Here is what you can do: http://jsfiddle.net/n7cyE/4/

$('#here_table').append('<table></table>');
var table = $('#here_table').children();
 for(i=0;i<3;i++){
    table.append( '<tr><td>' + 'result' +  i + '</td></tr>' );
}

Best regards!


this is most better

html

<div id="here_table"> </div>

jQuery

$('#here_table').append( '<table>' );

for(i=0;i<3;i++)
{
$('#here_table').append( '<tr>' + 'result' +  i + '</tr>' );

    for(ii=0;ii<3;ii++)
    {
    $('#here_table').append( '<td>' + 'result' +  i + '</tr>' );
    }
}

$('#here_table').append(  '</table>' );

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment