1

I wrote this script that filters through a table which contains numbers treated as strings. I converted the string to a number using parseInt(). See code below. I was then asked to also apply this to another cell which contains a string with either '1.00' or '0.00' and has a class called goal. I know I can duplicate the code below and change the parse to look for number == 1, but I am looking for a more efficient way to manage it.

<script type="text/javascript">
    $(document).ready(function () {
        $('td.completedPercent').filter(function (index) {
            return parseInt(this.innerHTML, 10) >= 90;
        }).css({ 'color': '#FFF', 'background-color': '#336633' });
    });
</script>

2 Answers 2

1

jsFiddle Demo

If you want to apply the filter to both classes of td then try selecting both at once, and inside of the filter, provide an or clause which differentiates them. Once the group is gathered, then you may apply your css to it. A class would be good here too.

<script type="text/javascript">
 $(document).ready(function () {
    $('td.completedPercent, td.goal').filter(function () {
     var t = $(this),i = parseInt(t.html(), 10);
     return (t.hasClass("goal") && i == 1) || i >= 90;})
     .css({ 'color': '#FFF', 'background-color': '#336633' });
 });
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

personally, I would write it this way:

$(function () {
    $('td').each(function () {
        var content = $(this).text();
        if (($(this).hasClass('completedPercent') && parseInt(content, 10) >= 90) || ($(this).hasClass('goal') && (content === '1.00' || content === '0.00'))) {
            $(this).css({
                'color': '#FFF',
                    'background-color': '#336633'
            });
        }
    });
});

but @TravisJ's answer works also.

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.