The Problem

You generated a table using jQuery Datatable without loading the page, using Ajax. You wish to change the HTML of cells in a certain column after the data is processed. How to do it?

For the sake of this example, we’ll say we want to switch the data in the first column of the table into a hyperlink.

The Solution

The problem described above can be easily solved by using the columnDefs option with data rendering.

columnDefs allows you to apply different behaviors on one or more of the columns in your table. But columnDefs alone is not enough. The behavior you want to apply is transforming the output in your table into something else, completely different sometimes. This can be achieved with data rendering.et’s see how columnDefs + data rendering is used.

Let’s see how columnDefs + data rendering is used.

The solution starts in line 5 where we are using columnDefs to modify our columns after we got the data for the table.

Targets

‘tragets’ defines on which columns the behavior (which we’ll later define) should be applied. In our case, we apply it on the first column (index starts at 0). You can choose to apply the same behavior on several different columns or apply different behaviors for different columns.

To apply the same behavior on the first and third column use the following syntax

To apply different behaviors on different columns

Let’s see what render does.

Render

With ‘render’ we define what we would like to do with the data, how to transform it to meet our expectations. ‘render’ function receives three parameters

  • data – the actual data (returned by the server or provided directly)
  • type – what type of data is being requested or managed. This might be difficult to grasp at the beginning but there are several types of data. There is the data we display, the data we sorted or the data we filtered. To learn more about this, have a look here.
  • row – we may want to use the data of a different row by using row[<index_number>] or row[<name of the row>] depends on the implementation.

Now that we understand what we can use, let’s see what was done in our example

With this line, we basically transform our data to be a link. To do so we use HTML <a> tag this way: <a href=$URL> string to display </a>.

If {{ agent.url }} is ‘http://server’ then we’ll get a link to ‘http://server/job/<data>’ and what will be displayed to the user depends on our data.

Finally, we return the data which is the modified variable with the link. It will be used and displayed on our table.