jquery – Add image to DataTables as per state

Question:

I walk around with the DataTables here and wanted to add an img according to the type of state. If the value is 0 puts an image and if it is 1 puts another image in the row .

Answer:

Given that you have a data set in the attribute data at startup of the columns of your DataTable, you can use the attribute render to modify the way the plugin will render each column.

In this attribute you can specify a function where you can define exactly which value will be mapped to which value.

Consider the example (taken from the documentation):

$('#example').dataTable( {
  "columnDefs": [ {
    "targets": 4,
    "data": "description",
    "render": function ( data, type, full, meta ) {
      return type === 'display' && data.length > 40 ?
        '<span title="'+data+'">'+data.substr( 0, 38 )+'...</span>' :
        data;
    }
  } ]
} );

Note that in this example there is only one column, but the same applies to an array of columns.

The function to transform the numbers 0 and 1 into an image could be something like:

function (data, type, full, meta) {
    var img = data == 0 ? 'desativado.jpg' : 'ativado.jpg';
    return type === 'display' ? '<img src="'+img+'">' : data;
}

Also note the comparison type === 'display' . This causes the image to be returned for display, but the original data to be used for sorting, filtering, etc. To change the value used in a search, for example, you can compare the value of type === 'filter' .

Finally, there is a related answer in SOen that might be useful to query. There you find the following example:

personTable = $("#person-table").DataTable({
    order: [1, "desc"],
    "autoWidth": false,
    ajax: {
        url: uri,
        dataSrc: "",
    },
    "columns": [
    { "data": "FirstName", "title": "Name" },
    { "data": "Address", "title": "Address" },
    { "data": "IsActive", "title": "Active" }
    ],
    "columnDefs": [
        {
            "render": function (data, type, row) {
                return row.FirstName + " " + row.LastName;
            },
            "targets": 1
        },
        {
            "render": function (data, type, row) {
                return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
            },
            "targets": 2
        }
    ]
});

It's pretty much the same, except here using Bootstrap icons instead of <img> tags.

Scroll to Top
AllEscort