Background color for rows are set based on "even/odd". Could this be used based on cell value?

Background color for rows are set based on "even/odd". Could this be used based on cell value?

TomasHelsenTomasHelsen Posts: 5Questions: 2Answers: 0
edited February 23 in Free community support

So I want all rows with the same "env nr" to have the same background color.
Anyone know how to achieve this?
Table data:
[env nr]  [name]   [group]
1     t1     test
1     t2     test
2     t3     prod
2     t4     prod
3     t5     test
3     t6     test
3     t7     prod
4     t8     prod
5     t9     test

Thanks!

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Use createdRow to assign a specific class to the row based on whatever logic you want to use in the function.

    Or if the data might change (e.g. you are using Editor, or updating the row some other way), use rowCallback to update the row's class whenever the table is redraw.

    Allan

  • TomasHelsenTomasHelsen Posts: 5Questions: 2Answers: 0

    Thanks for extremely quick answer!
    In the css file the classes are called odd and even.
    So I'm after a solution that will set this class based on if the cell value in [env nr] is an even or odd number. Guess I'll have to create a if statement to achieve that?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Correct - as I say, use createdRow with a function that adds a class to the row. Then in your CSS give that class a background colour. You don't need to think about the odd and even classes at all.

    Here is a trivial example: https://live.datatables.net/botidifo/1/edit .

    Allan

  • TomasHelsenTomasHelsen Posts: 5Questions: 2Answers: 0

    Thanks, have a bit of a struggle here :-) It ended up with asking co-pilot without any success. this is the code it suggests:
    {
    "targets": 0,
    "createdRow": function (row, data) {
    if ($(row).index() % 2 === 0) {
    row.classList.add('even');
    } else {
    row.classList.add('odd');
    }
    }
    }

    but it doesn't work, not sure if I can use the default class in css file or if I need to create new classes?

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Don't use odd and even. Sorry if I wasn't clear about that before.

    Add a class based on the data in the row, like in my example. If I've understood your question, that is what you want, yes?

    Create your own class name and put the definition for it in your CSS, like in the example I provided.

    Allan

  • TomasHelsenTomasHelsen Posts: 5Questions: 2Answers: 0

    Thanks, then I'll know how to proceed
    cheers!

Sign In or Register to comment.