Jon Erickson
Jon Erickson

Reputation: 1976

jQuery Datatables add column on condition

I have a jQuery datatable that I use to display data after making a AJAX request. However, I want to add a third column to the table if the current user is an administrator so that they can delete an entry. How would I add a third column based on a conditional statement? Thanks.

Code:

    // Create our AJAX request to get the data
    new Ajax.Request( combat_record_link,
    {
        method: 'get',
        evalJSON: 'force',
        parameters: {
            'md5check': ipb.vars['secure_hash']
        },
        onSuccess: function(t)
        {
            if( Object.isUndefined( t.responseJSON ) )
            {
                alert( "Bad Request" );
            }
            else if ( t.responseJSON['error'] )
            {
                alert( t.responseJSON['error'] );
            }
            else
            {
                jQuery('#combat_record').dataTable( {
                    "data": t.responseJSON,
                    "paging": true,
                    "ordering": true,
                    "order": [[ 0, "desc" ]],
                    "info": false,
                    "columns": [
                        { "title": "Date", "width": "10%", "data": "date"},
                        { "title": "Entry", "width": "90%", "data": "entry", "orderable": false},
                    ]
                });                 
            }
        }
    });

Upvotes: 5

Views: 8833

Answers (1)

TheDude
TheDude

Reputation: 3952

You can just do:

var columns = [{ "title": "Date", "width": "10%", "data": "date"},
               { "title": "Entry", "width": "90%", "data": "entry", "orderable": false}];

if(isAdmin){
   columns.push({"title": "Delete", ...});
}

jQuery('#combat_record').dataTable( {
                    "data": t.responseJSON,
                    "paging": true,
                    "ordering": true,
                    "order": [[ 0, "desc" ]],
                    "info": false,
                    "columns": columns
});

Upvotes: 13

Related Questions