DGOU182
DGOU182

Reputation: 11

I'm trying to use jquery to hide any row in a table that has a negative dollar amount

I have the following table row in a table. I'm trying to use jquery to hide any row in a table that has a negative dollar amount. How can I test if the text in a div has a negative number, and how do I add the class to the row class so I can hide it.

<tr class="Cont">
        <td>Name of something</td>
        <td><div class="negMoney">$-1,000.22</div></td>

        </tr>

Upvotes: 0

Views: 52

Answers (2)

Shiv Kumar Baghel
Shiv Kumar Baghel

Reputation: 2480

$("tr:has(div:contains('-'))").hide(); will search - (negative) in each DIV of TD and then this solution will not work if any div comes in TD in future.

In below solution it will search negative value only in negMoney class which is 2nd TD of row.

$(".negMoney").each(function(i){
   var val = $(this).html();
   var isNegative = Number((val.substr(1)).replace(/\,/g,'')) < 0;       
   if(isNegative) { 
      $("tr:eq( "+ i +" )").hide(); 
   }
});

Upvotes: 0

steve v
steve v

Reputation: 3540

Use the has and contains selectors in jQuery.

$("tr:has(div:contains('-'))").hide();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table>
  <tr class="Cont">
        <td>Name of something a</td>
        <td><div class="negMoney">$-1,000.22</div></td>

   </tr>
  <tr class="Cont">
        <td>Name of something b</td>
        <td><div class="negMoney">$1,000.22</div></td>

   </tr>
  <tr class="Cont">
        <td>Name of something c</td>
        <td><div class="negMoney">$-1,000.22</div></td>

   </tr>
  <tr class="Cont">
        <td>Name of something d</td>
        <td><div class="negMoney">$1,000.22</div></td>

   </tr>
  <tr class="Cont">
        <td>Name of something e</td>
        <td><div class="negMoney">$1,000.22</div></td>

   </tr>   

Upvotes: 2

Related Questions