1

I am adding a div to my jQuery dataTable using render call back function:

columns: [
            {
                data: 'FirstStep',
                render: function (data, type, row) {
                    if (data === 4) {
                        return '<div class="red-circle"></div>';
                    }
                    else if (data === 3) {
                        return '<div class="yellow-circle"></div>';
                    }
                    else if (data === 2) {
                        return '<div class="blue-circle"></div>';
                    }
                    else if (data <= 1) {
                        return '<div class="green-circle"></div>';
                    }
                }
            },
            --Other columns 
            }
        ]

This works fine but If I extract render call back to a function ( need to reuse several times )and trying code as below , it does not work.

function renderCellItems(data, type, row) {
        if (data === 4) {
            return '<div class="red-circle"></div>';
        }
        else if (data === 3) {
            return '<div class="yellow-circle"></div>';
        }
        else if (data === 2) {
            return '<div class="blue-circle"></div>';
        }
        else if (data <= 1) {
            return '<div class="green-circle"></div>';
        }
    }

...............

{
    data: 'FirstStep',
    render: renderCellItems(data, type, row)
}
3
  • check arguments Commented Jun 1, 2018 at 8:53
  • Add in a sample table to work with. Commented Jun 1, 2018 at 8:55
  • It takes 3 arguments and we are passing 3 arguments to new function Commented Jun 1, 2018 at 8:56

1 Answer 1

1

The issue is because you are currently supplying the response from that function as the render property, ie. the HTML string, yet the property expects a function.

You instead need to provide the reference to that function. To do that, remove the trailing parentheses and arguments:

{
  data: 'FirstStep',
  render: renderCellItems
}

Also note that you can improve the logic by using an array to store the return values:

function renderCellItems(data, type, row) {
  var classes = ['green-circle', 'blue-circle', 'yellow-circle', 'red-circle'];
  return '<div class="' + classes[Math.max(data, 1) - 1] + '"></div>';
}

console.log(0, renderCellItems(0));
console.log(1, renderCellItems(1));
console.log(2, renderCellItems(2));
console.log(3, renderCellItems(3));
console.log(4, renderCellItems(4));

Sign up to request clarification or add additional context in comments.

Comments

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.