foobar
foobar

Reputation: 97

a cleaner or simpler way to write this jquery function?

function foo() {
    $('#bar > table > tbody > tr').each(function () {
        $(this).find('td:nth-child(3)').text() == '1' && $(this).find('td:nth-child(1)').css('background-color', 'green');
        $(this).find('td:nth-child(3)').text() == '2' && $(this).find('td:nth-child(1)').css('background-color', 'yellow');
        $(this).find('td:nth-child(3)').text() == '3' && $(this).find('td:nth-child(1)').css('background-color', 'red');

    });
}
  1. Is this the right approach to make style changes to a mvc grid column based on value in another column in the same row?
  2. Is there a better/cleaner or simpler way to achieve similar functionality?

Upvotes: 1

Views: 45

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370689

Use an object indexed by text to find, whose values are the colors to set:

const colorsByText = {
    1: 'green',
    2: 'yellow',
    3: 'red'
};
function foo() {
    $('#bar > table > tbody > tr').each(function () {
        const text = $(this).find('td:nth-child(3)').text();
        const color = colorsByText[text];
        if (color) {
            $(this).find('td:nth-child(1)').css('background-color', color);
        }
    });
}

If the text will always be one of those 3 properties, you can remove the if check - or, even better, use an array instead of an object:

const colors = ['green', 'yellow', 'red'];
function foo() {
    $('#bar > table > tbody > tr').each(function () {
        const text = $(this).find('td:nth-child(3)').text();
        const color = colors[text - 1];
        $(this).find('td:nth-child(1)').css('background-color', color);
    });
}

Upvotes: 1

Related Questions