1

I am using jQuery DataTables in my project. I am fetching data as JSON using ajax and initializing datatable using that, but if data column contains value as ABC XYZ (Note there are 2 spaces between ABC and XYZ) multiple whitespaces are not preserved in rendered output.

JSP Code

<table id="marketViewStatusDT" class="display" style="cellspacing:0;width:100%;background-color: #ffffff;" >
    <thead>
        <tr>
            <th style="width:12%;height:30px;" class="aleft">UTI</th>
            <th style="width:5%;height:30px;" class="aleft">Source&nbsp;&nbsp;</th>                         
        </tr>
    </thead>
</table>

JS CODE

marketViewStatusDT = $("#marketViewStatusDT").DataTable( {
    "sDom": '<"H"l<"toolbar">p>t<"F"ip>',
    "bDestroy":true,
    "bProcessing" : true,
    "bServerSide" : true,
    "bLenthChange" : false,
    "bJQueryUI" : false,
    "lengthMenu": [[20, 50, 100], [20, 50, 100]],
    "bSort" : true,
    "bFilter": false,
    "bPaginate": true,
    "bSearchable": true,
    "pagingType": "full",
    "scrollY": calcDataTableHeight(),
    "scrollX": true,
        "sAjaxSource" : "fetchData.html",
        "aoColumns": [
            { "mData": "uti",},
            { "mData": "source",}           
        ],
}); 
Sascha Gottfried
  • 3,303
  • 20
  • 30
Rahul Agrawal
  • 8,913
  • 18
  • 47
  • 59

3 Answers3

2

Using this CSS snippet you instruct the browser to preserve whitespaces within the table tag with id attribute marketViewStatusDT:

#marketViewStatusDT{
    white-space:pre; 
}

If you want wrapping to still work:

#marketViewStatusDT{
    white-space:pre-wrap; 
}
Sascha Gottfried
  • 3,303
  • 20
  • 30
1

In JQuery DataTables you have to allow white spaces for <td>. Its not enabled by default. Therefore, for specified td column you can write createdRow for allow white spaces for specific column as following example

Datatable JQuery:

$(document).ready(function() {
    $('#example').DataTable( {
        "createdRow": function ( row, data, index ) {
            $('td', row).eq(1).addClass('whitespace');
        }
    } );
} );

CSS:

td.whitespace {
    white-space: pre;
}
PNP
  • 361
  • 5
  • 17
0

HTML always renders 1 or more spaces a 1 space. use &nbsp; if you need more then one

Jelle Keizer
  • 723
  • 5
  • 9