Jay
Jay

Reputation: 406

Jquery DataTables Two Fields in One Column using IF statement

I have a jQuery datatable using AJAX. I would like to have two fields together in one column and also use if statements for both fields.

I can do two fields together:

  { 
     "data" : function (data, type, dataToSet) {return data.primary + "<br/>" + data.proctor;
   }},

I have added some styling a based off an if statement:

    {
      "data" : "primary",
      "render" : function(primary) {
          if (!primary) {
                return '<i class="fa fa-ban"></i> primary';
          } else {
                 return '<i style="color: green" class="fa fa-check"></i> primary';
                    }
                }
            },
   {
      "data": "proctor",
      "render": function (proctor) {
          if (!primary) {
                 return '<i class="fa fa-ban"></i> proctor';
          } else {
                 return '<i style="color: green" class="fa fa-check"></i> proctor';
                    }
                }
            },

How would I combine the two fields into one column and still have the if/else statement?

Upvotes: 1

Views: 1838

Answers (1)

davidkonrad
davidkonrad

Reputation: 85528

You can combine the two fields by adding a null column with its own render method :

columns: [
  ...
  { data: null,
    render: function(data, type, full) {
      var ret = '';
      if (!full.primary) {
        ret += '<i class="fa fa-ban"></i> primary';
      } else {
        ret += '<i style="color: green" class="fa fa-check"></i> primary';
      }
      if (!full.proctor) {
        ret += '<i class="fa fa-ban"></i> proctor';
      } else {
        ret += '<i style="color: green" class="fa fa-check"></i> proctor';
      }
      return ret;
    }
  }
]

BTW: I think that ternarys in this case would be better than if..else. At least more readable :

var ret = !full.primary
   ? '<i class="fa fa-ban"></i> primary'
   : '<i style="color: green" class="fa fa-check"></i> primary';

ret += !full.proctor
   ? '<i class="fa fa-ban"></i> proctor'
   : '<i style="color: green" class="fa fa-check"></i> proctor';

return ret;

Upvotes: 2

Related Questions