Populate the caption of a table from json

Populate the caption of a table from json

iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

Hello,
I have a table which will display a customer's data after login. How can I populate the caption of the table with the username supplied in the json data?

{
   "username": [
  [
    "item1",
    "item2",
    "item3"
     ]
   ]
 }

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,348Questions: 36Answers: 394

    What is your data source, and how are you building your HTML?

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    How can I populate the caption of the table with the username supplied in the json data?

    You need to add it yourself using jQuery or DOM methods. DataTables does not provide an API to add the caption tag.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    I've built a jsfiddle of my table, which includes the caption tag.
    http://jsfiddle.net/lbriquet/p2wffs95/

    I couldn't figure out how to make a json call work in a jsfiddle though.

    On my server I am calling the json like this:

    $(document).ready(function () {
        /* Initialise datatables */
        var oTable = $('#example').dataTable({
            "ajax": {
                "url": "/dyn/meeting/f?p=MEETINGS:MYMEETINGS",
                "type": "POST",
                "dataSrc": "mydata"
       },
       etc.
    

    I would like to pick up the username, from the json file. For example: "Mike Smith" and populate the caption tag with it. My json is built like this for now:

    {"Mike Smith": [
     [ "Monday","<span></span>","Astronomy","yes","<span class='yes'>X</span>","<span class='no'>X</span>","Hall of Science","Galileo Planetarium" ],
     [ "Monday","<span></span>","Art","no","<span class='no'>X</span>","","Fine Arts Building","Monet" ]
    ]
    }
    

    Could you help me to get the username to populate the table caption?
    Thank you in advance for your help!

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    Use initComplete to which the JSON is passed. Then grab the object key from it (presumably you know it in advance since you'll need to tell DataTables what it is using ajax.dataSrc - I don't really understand why you have Mike Smith in your data and mydata in the configuration). Then just create a tag an insert it using jQuery.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    Hi Allan,
    I can include the username in the json file generated after authentication... so I will not know in advance the username. I am not sure how to structure the json to provide something that I can pick up for the caption. So I put Mike Smith in the json as an example of a username I'd like to pick up. My thought was to be able to call the json with a variable like "username" and then use the value for the caption. Since I didn't know how to do this in the javascript I I used mydata. I've look at all the examples I could find, but I haven't been able to figure it out... which is why I decided to submit a question to the forum. I would really appreciate your help... I'm so close to having a great solution with your great datatables tool!

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin
    edited July 2015

    Why not just add "caption": "Mike Smith" to the JSON? Then you can use json.caption to access the caption property.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    Thank you Allan!
    I've adjusted my json accordingly:

    {
    "caption": "Mike Smith",
    "data": [
     [ "Monday","<span></span>","Astronomy","yes","<span class='yes'>X</span>","<span class='no'>X</span>","Hall of Science","Galileo Planetarium" ],
     [ "Monday","<span></span>","Art","no","<span class='no'>X</span>","","Fine Arts Building","Monet" ]
    ]
    }
    

    I'm accessing my data with "dataSrc": "data"

    $(document).ready(function () {
        /* Initialise datatables */
        var oTable = $('#example').dataTable({
            "ajax": {
                "url": "/dyn/meeting/f?p=MEETINGS:MYMEETINGS",
                "type": "POST",
                "dataSrc": "data"
       },
       etc.
    

    Can you tell me how to use json.caption to populate the table caption?

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    Yes, is is just basic jQuery

    $('<caption/>').html( json.caption ).appendTo( '#myDataTable' );
    

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    Hi Alan,
    Thank you very much for your help!

    I've added the appendTo in a initComplete, but it is not functioning. I'm wondering whether it requires that everything uses the new naming conventions and .DataTable?

    Here is the code I am using... could you take a look and let me know what I'm doing wrong?

    /* Custom filtering function which will filter data in column four between two values */
    $.fn.dataTableExt.afnFiltering.push(function (oSettings, aData, iDataIndex) {
        var filter = $('input[name=RadioGroup1]:checked').data('course'),
            course = aData[3];
        return course == filter || filter == "*";
    });
    $(document).ready(function () {
        /* Initialise datatables */
        var oTable = $('#example').dataTable({
            "ajax": {
                "url": "data/coursedata.txt",
                "caption": "caption",
                "dataSrc": "data"
            },
            "initComplete": function( settings, json ) {
                $('<caption/>').html( json.caption ).appendTo( '#example' );
            },
            "columnDefs": [{
                "visible": false,
                    "targets": [0, 3]
            }, {
                "bSortable": false,
                    "aTargets": [0, 1, 2, 3, 4, 5, 6, 7]
            }, {
                className: "centerit",
                    "targets": [4, 5]
            }, {
                className: "nobreak",
                    "targets": [7]
            },
            ],
                "order": [
                [0, 'asc']
            ],
                "bPaginate": false,
                "iDisplayLength": 100,
                "bLengthChange": false,
                "oSearch": {
                "bSmart": false
            },
                "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                var sStarIcon;
                var sHighlightam;
                var sHighlightpm;
                var sAttend;        
                if (aData[2] == "Astronomy" && aData[3] == "yes") {
                    sStarIcon = "glyphicon glyphicon-star"
                } else if (aData[2] == "Astronomy" && aData[3] == "no") {
                    sStarIcon = "glyphicon glyphicon-star-empty"
                } else if (aData[2] == "Theater" && aData[3] == "yes") {
                    sStarIcon = "glyphicon glyphicon-heart"
                } else if (aData[2] == "Theater" && aData[3] == "no") {
                    sStarIcon = "glyphicon glyphicon-heart-empty"
                } else if (aData[2] == "Art") {
                    sStarIcon = "glyphicon glyphicon-picture"
                } else if (aData[2] == "Botany") {
                    sStarIcon = "glyphicon glyphicon-leaf"
                } else if (aData[2] == "Finance") {
                    sStarIcon = "glyphicon glyphicon-usd"
                } else if (aData[2] == "Geography") {
                    sStarIcon = "glyphicon glyphicon-globe"
                } else if (aData[2] == "History") {
                    sStarIcon = "glyphicon glyphicon-header"
                } else if (aData[2] == "Music") {
                    sStarIcon = "glyphicon glyphicon-music"
                }
                if (aData[3] == "yes" ){
                    sAttend = "going"
                } else {sAttend = "notgoing"}        
                if (aData[4] == "<span class='yes'>X</span>" ){
                    sHighlightam = "highlight"
                } else {sHighlightam = ""} 
                if (aData[5] == "<span class='yes'>X</span>" ){
                    sHighlightpm = "highlight"
                } else {sHighlightpm = ""}         
                $('td:eq(0) span', nRow).addClass(sAttend + ' ' + sStarIcon);
                $('td:eq(2)', nRow).addClass(sHighlightam );
                $('td:eq(3)', nRow).addClass(sHighlightpm );
            return nRow;
            },
                "drawCallback": function (settings) {
                var api = this.api();
                var rows = api.rows({
                    page: 'current'
                }).nodes();
                var last = null;
    
                api.column(0, {
                    page: 'current'
                }).data().each(function (group, i) {
    
                    if (last !== group) {
                        $(rows).eq(i).before(
                            '<tr class="group"><td colspan="7">' + group + '</td></tr>');
                        last = group;
                    }
                });
            }
        });
        /* Add event listeners to the two range filtering inputs */
        $('#showcourse').change(function () {
            oTable.fnDraw();
            $('#btn1').addClass('active');
            $('#btn2').removeClass('active');
        });
        $('#showall').change(function () {
            oTable.fnDraw();
            $('#btn1').removeClass('active');
            $('#btn2').addClass('active');
        });
    
        $('[name="RadioGroup1"]').change(function () {
            oTable.fnDraw();
        });
    });
    // Setup DataTable Defaults
    $.extend($.fn.dataTable.defaults, {
        fnInitComplete: function (oSettings, json) {
            // Add "Clear Filter" button to Filter
            var btnClear = $('<button class="btnClearDataTableFilter btn btn-link"><span class="glyphicon glyphicon-remove"></span></button>');
            btnClear.prependTo($('#' + oSettings.sTableId).parents('.dataTables_wrapper').find('.dataTables_filter label'));
            $('#' + oSettings.sTableId + '_wrapper .btnClearDataTableFilter').click(function () {
                $('#' + oSettings.sTableId).dataTable().fnFilter('');
            });
        }
    });
    

    My json looks like this:

    {
    "caption": "Mike Smith",
    "data": [
     [ "Monday","<span></span>","Astronomy","yes","<span class='yes'>X</span>","<span class='no'>X</span>","Hall of Science","Galileo Planetarium" ],
     [ "Monday","<span></span>","Art","no","<span class='no'>X</span>","","Fine Arts Building","Monet" ]
    ]
    }
    
  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    You can't have both initComplete and fnInitComplete . You must use only one (since one is just an alias of the other it will overwrite the other).

    Try removing your "Setup DataTable Defaults" block and see if it works. If it doesn't please link to a test page showing the issue.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    Hi Allan,
    I've removed the "Setup DataTable Defaults" block, but I am still not able to populate the caption. I've created a new jsfiddle calling the json file.
    http://jsfiddle.net/lbriquet/xmbz73ev/

    Could you please take a look and let me know what I've done wrong?
    Thank you so much for your help!!

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin
    Answer ✓

    The caption is being shown at the top of the table in your example.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1
    edited July 2015

    I don't understand... the caption is not shown.

    <table id="example" class="table table-hover table-bordered display responsive nowrap" cellspacing="0" width="100%">
                <caption></caption>
    

    The caption tag should be populated with the json caption data "Mike Smith"

    "initComplete": function (settings, json) {
                $('<caption/>').html(json.caption).appendTo('#example');
            },
    

    Picking up the json data for the caption:

    {
    "caption": "Mike Smith",
    "data": [
    
  • mrd05dmrd05d Posts: 45Questions: 6Answers: 3

    The caption is there. If you look at your jsfiddle it doesn't update html window in fiddle itself. If you use inspect in chrome or other developer tools suite in another browser on the preview window you will see it indeed placed mike smith in the caption... I don't think jsfiddle updates the html window portion if you manipulate dom after load etc.

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    There are two captions in the HTML. The first one empty. You could use jQuery to remove that, or just not put it there in the first place.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    I found the problem... it needt to be prependTo, instead of appendTo, since the caption tag is at the top of the table.

    $('<caption/>').html(json.caption).prependTo('#example');
    

    Thank you so much for your help Alan!!!

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    Strictly by HTML specs, yes it should be the first element. I doubt any browser would struggle with it anywhere in the table tag though.

    However, good to hear you've got it working now.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    Hi again Alan,
    Just one more question...
    How can I include my reset search button in the initComplete?
    I was calling it from fnInitComplete using a $.extend($.fn.dataTable.defaults, at the end of my code.

    Here is a link to my jsfiddle:
    http://jsfiddle.net/lbriquet/q572fud9/

    This is the old fnInitComplete I would like to include in the initComplete.

    $.extend($.fn.dataTable.defaults, {
        fnInitComplete: function (oSettings, json) {
            // Add "Clear Filter" button to Filter
            var btnClear = $('<button class="btnClearDataTableFilter btn btn-link"><span class="glyphicon glyphicon-remove"></span></button>');
            btnClear.prependTo($('#' + oSettings.sTableId).parents('.dataTables_wrapper').find('.dataTables_filter label'));
            $('#' + oSettings.sTableId + '_wrapper .btnClearDataTableFilter').click(function () {
                $('#' + oSettings.sTableId).dataTable().fnFilter('');
            });
        }
    });
    

    Thank you again for your help!!!!!!!!

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1
    edited July 2015

    I've managed to successfully add the reset search button this with.

                "initComplete": function (settings, json) {
                $('<caption/>').html(json.caption).prependTo('#example');
                var btnClear = $('<button id="clearsearch" class="btnClearDataTableFilter btn btn-link"><span class="glyphicon glyphicon-remove"></span></button>');
                $('.dataTables_filter').prepend(btnClear);
                  
            },
    

    but I've not been able to get the click function working:
    $('.btnClearDataTableFilter').click(function () { oTable.search( '' ).draw(); })

    Here is a my revised jsfiddle... could you please take a look. I think the reset seach click function must be very close to working.

    http://jsfiddle.net/lbriquet/8hhyxka1/1/

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin
        $('.btnClearDataTableFilter').click(function () { 
            oTable.search( '' ).draw();
        }); 
    

    This code is currently being executed before the clear button has been added to the document. It runs because initComplete since you are using async loading of data.

    Either make it a delegated event or just stick it inside the initComplete function as well.

    Allan

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1
    edited July 2015

    I've moved the code inside the initComplete function... but the click function is still not working. I get a Firebug error TypeError: oTable.search is not a function

    I've my updated jsfiddle.
    http://jsfiddle.net/lbriquet/gjaumzqc/3/

    Could you please take a look?

  • iecwebmastiecwebmast Posts: 66Questions: 9Answers: 1

    I think the problem has to do with converting everything to datatables 1.10. I tried changing the datatables Initialise call to use the new camelCase

    $(document).ready(function () {
        /* Initialise datatables */
        var oTable = $('#example').DataTable({
    

    And now my reset search button! But... my filters don't.

    http://jsfiddle.net/lbriquet/rd8egf83/

    I've tried to convert everything to the new new camelCase for datatables 1.10... but then everything breaks.

    http://jsfiddle.net/lbriquet/rd8egf83/1/

    How can I resolve this?

  • allanallan Posts: 61,653Questions: 1Answers: 10,094 Site admin

    Looks like you've updated the rowCallback parameters:

    "rowCallback": function (row, data, iDisplayIndex, iDisplayIndexFull) {

    But not now those parameters are called (nRow specifically should be row now): http://jsfiddle.net/rd8egf83/2/

    Allan

This discussion has been closed.