Home > other >  Jquery coloring table cells according to condition and values
Jquery coloring table cells according to condition and values

Time:11-20

Trying to colour table rows that contain years<= 2004 in the second column and the third column should have value "Ne". What I am getting now is colored rows that contain only values in the third column "Ne" and condition years<=2005 is ignored. Is there some way to write condition using &&, or my syntax is bad?

$(function(){
        $("#randa").click(function(){
          $("#lentele td:nth-child(2)").each(function()
          {
            if (parseInt($(this).text()) <=2005)
            {
              
              $("#lentele td:nth-child(3)").each(function()
              {
                if ($(this).text() == "Ne")
                {
                  $(this).parent("tr").addClass('spalvinti');
                  
                }

                
              }
              
            )
            
            }
          })
        })

});

enter image description here

CodePudding user response:

When you find applicable cell with text Ne, it needs to be in the same row as the matching cell with the year. The code with problem is finding all cells with Ne instead.

I would process row by row as below:

$("#randa").click(function(){
  $("#lentele tr").each(function() {
    if (parseInt($(this).children('td:nth-child(2)').text()) <= 2005
        && $(this).children('td:nth-child(3)').text() === 'Ne') {
      $(this).addClass('spalvinti');
    }
  });
});
table { border: 1px solid #eee; }
tr.spalvinti { background-color: green; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="randa">
  <table id="lentele">
    <tbody>
      <tr>
        <td>1</td><td>2010</td><td>Taip</td>
      </tr>
      <tr>
        <td>2</td><td>1999</td><td>Ne</td>
      </tr>
      <tr>
        <td>3</td><td>2001</td><td>Ne</td>
      </tr>
      <tr>
        <td>4</td><td>2004</td><td>Ne</td>
      </tr>
      <tr>
        <td>5</td><td>2008</td><td>Ne</td>
      </tr>
    </tbody>
  </table>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related