1

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?

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for your help. I agree the ternarys are more readable. Thanks for providing both examples.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.