Search code examples
jqueryjquery-selectors

Selecting a table row that does not have a specific class


I am trying to focus an input inside a table row, but I need to 'jump' some tr's that have some specific class.

I already tried with next/nextAll/nextUntil but the only thing I can do is select the last input, and not the next one. In my example, the input to be focused in is the third one, but it is focusing the last one.

<table>

  <tr class="product selected">
    <td>
      <input type="text" class="foo">
    </td>
  </tr>
  <tr class="info">
  </tr>

  <tr class="product to_ignore">
    <td>
      <input type="text" class="foo">
    </td>
  </tr>
  <tr class="info to_ignore">
  </tr>

  <tr class="product">
    <td>
      <input type="text" class="foo">
    </td>
  </tr>
  <tr class="info">
  </tr>

  <tr class="product">
    <td>
      <input type="text" class="foo">
    </td>
  </tr>
  <tr class="info">
  </tr>

</table>

$('tr.selected').nextAll('.product').not('.to_ignore, .info').find(".foo").select();

https://jsfiddle.net/s7wo5fzm/


Solution

  • Your problem was that you selected every .product and not only the first that matched your criteria. Because of that your code first sleected the third input but then selected the fourth ans deselected the third again.

    So basically all you have to do is add .first() before .find():

    var button = $("button");
    
    button.on("click", function(){
    
    $('tr.selected').nextAll('.product').not('.to_ignore, .info').first().find(".foo").select();
      $('tr.selected').removeClass('selected');
      $('input:focus').closest('tr').addClass('selected');
      
    })
    body {
      background: white;
      padding: 20px;
      font-family: Helvetica;
    }
    
    table {
      border: 1px solid black;
    }
    
    tr.selected {
      background-color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button type="button" id="jump">Jump</button>
    
    <table>
    
      <tr class="product selected">
        <td>
          <input type="text" class="foo">
        </td>
      </tr>
      <tr class="info">
      </tr>
    
      <tr class="product to_ignore">
        <td>
          <input type="text" class="foo">
        </td>
      </tr>
      <tr class="info to_ignore">
      </tr>
    
      <tr class="product">
        <td>
          <input type="text" class="foo">
        </td>
      </tr>
      <tr class="info">
      </tr>
    
      <tr class="product">
        <td>
          <input type="text" class="foo">
        </td>
      </tr>
      <tr class="info">
      </tr>
    
    </table>