Ron
Ron

Reputation: 1731

jQuery Hiding element based on previous row td value

I have a table like this:

<table>
    <tr>
        <td>
            <a href="/payinvoice/1">Pay Invoice 1</a>
            <span class="paid hidden">False</span>
        </td>
    </tr>
    <tr>
        <td>
            <a href="/payinvoice/2">Pay Invoice 2</a>
            <span class="paid hidden">False</span>
        </td>
    </tr>
</table>

and I need to hide the Pay Invoice 2 link if the value of the span in the previous row td is False.

I came up with this:

$('span.paid').each(function () {
    if ($(this).prev("span.paid").text() == "False") {            
        $(this).prev("a").addClass("hidden");
    }
});

but it doesn't work. Any tips? Thanks!

Upvotes: 0

Views: 1328

Answers (4)

Chamika Sandamal
Chamika Sandamal

Reputation: 24332

try this code,

$('tr').each(function() {
    if ($("span.paid", $(this)).text() == "False") {
        $("a", $(this).next('tr')).addClass("hidden");
    }
});

Working sample

Upvotes: 1

Purag
Purag

Reputation: 17071

Here's what you're looking for:

$('span.paid').each(function () {
    var prev = $(this).parents('tr').prev().find('span.paid').text();
    if (prev=='False') {            
        $(this).prev().hide();
    }
});

Firstly, we're setting the text to the prev variable for organization purposes.

We first find the tr element that holds the span.paid the function is being applied to and selecting the previous tr. We search for span.paid in that tr, get its text, and match it to the string 'False' in the if() function.

Big explanation, but simple results.

Upvotes: 1

Riz
Riz

Reputation: 10246

  $('span.paid').each(function () {
      if ($(this).parents('tr').prev().find("span.paid").text() === "False") {            
          $(this).prev("a").addClass("hidden");
      }
  });

Upvotes: 1

Mathias Bynens
Mathias Bynens

Reputation: 149804

$('span.paid').each(function() {
    var $this = $(this);
    if ($.trim($this.closest('tr').prev('tr').find('span.paid').text()) == 'False') {            
        $this.prev('a').addClass('hidden');
    }
});

Upvotes: 1

Related Questions