Make a HTML Table with jQuery

For a project I was working on, I needed a quick, simple solution to make a dynamic table based on data sent back from an AJAX call. I used jQuery to build and manipulate the table HTML, since it was quick to use jQuery and it’s already in my project.

After considering a few different ways to approach this, I decided different arrays would be the easiest way to handle the data. The data looks like this:

var data = {
    k: ['Name', 'Occupation', 'Salary', 'Roommate'],
    v: [['Chandler', 'IT Procurement Manager', '$120,000', 'Joey'],
        ['Joey', 'Out-of-work Actor', '$50,000', 'Chandler'],
        ['Monica', 'Chef', '$80,000', 'Rachel'],
        ['Rachel', 'Assistant Buyer', '$70,000', 'Monica'],
        ['Ross', 'Dinosaurs', '$100,000', 'No Roommate']]
}

It’s a JavaScript object with two keys: one for the header that I abbreviated k and the main data values which have the key of v. The header is just an array of strings, while the values are an array of arrays. I specifically designed this code to work within these parameters, so there could be more checks built in, but the data source is rather rigid.

To make the Table class, I defined the attributes:

function Table() {
    //sets attributes
    this.header = [];
    this.data = [[]];
    this.tableClass = ''
}

Using this prototype code is a little bit of overkill, but it can be reused and extended. I plan on having the application update with new data and possibly other features. Creating a prototype allows that to be a little bit easy and cleaner.

I have three setter methods, which just allow the Table object to have it’s attributes set and have the data set.

Table.prototype.setHeader = function(keys) {
    //sets header data
    this.header = keys
    return this
}

Table.prototype.setData = function(data) {
    //sets the main data
    this.data = data
    return this
}

Table.prototype.setTableClass = function(tableClass) {
    //sets the table class name
    this.tableClass = tableClass
    return this
}

All the methods I’ve written have return this in them. That allows method chaining, which makes the implementation of the code a lot simpler. The meat of the code is in the build method.


Table.prototype.build = function(container) {

    //default selector
    container = container || '.table-container'
 
    //creates table
    var table = $('
').addClass(this.tableClass) var tr = $('') //creates row var th = $('') //creates table header cells var td = $('') //creates table cells var header = tr.clone() //creates header row //fills header row this.header.forEach(function(d) { header.append(th.clone().text(d)) }) //attaches header row table.append($('').append(header)) //creates var tbody = $('') //fills out the table body this.data.forEach(function(d) { var row = tr.clone() //creates a row d.forEach(function(e,j) { row.append(td.clone().text(e)) //fills in the row }) tbody.append(row) //puts row on the tbody }) $(container).append(table.append(tbody)) //puts entire table in the container return this }

I’ve annotated most of the code, but basically this creates jQuery objects for each of part of the table structure: the table (table), a row (tr), a header cell (th) and a normal table cell (td). The clone() method is necessary so that jQuery creates another HTML element. Otherwise it will keep on removing, modifying and appending the same element.

Using the prototype we just created is rather easy, we did the hard part already. We use the new keyword to instantiate a new object. This allows us to create many different independent Table objects which can be manipulated individually within the application.

//creates new table object
var table = new Table()
    
//sets table data and builds it
table
    .setHeader(data.k)
    .setData(data.v)
    .setTableClass('sean')
    .build()

Above is the short snippet of code which has method chaining. This allows us not to have to write separate lines of code for each method which would look like table.setData(). I used the setHeader() to set the array (data.k) which populates the table’s header. The setData() method sets the array of an array (data.v) as the source of the data for the rest of the table.

Finally, the build() method uses the data we just set to actually run the code that manipulates the HTML and this is what you see in your web browser.

Before using it on a web page, there has to be some HTML. (And some CSS so that the table looks decent.) The most important part is that the div container has the class of "table-container". The Table class is by default looking for that class to append the table to. You can customize that by changing using a jQuery selection string as a parameter in the table.build([jQuery selection string]) method.




    
    
    

    





Above is an working version of all the code from above. The full code I used for this post can be found on my GitHub .