kumar_v kumar_v - 5 months ago 15
jQuery Question

count Table rows which have non-empty textbox

How to count the number of table rows which are having non-empty textbox in its

<td>
?

I have tried something like below but it counts all the rows.

$("#sample_table input[value!=\"\"]").closest("tr",$(this)).length;

Answer

You can use .filter() to get the tr elements.

Reduce the set of matched elements to those that match the selector or pass the function's test.

Code

var trElements = $("#sample_table tr").filter(function(){
    //Get Non Empty inputs
    var nonEmptyInputs = $(this).find('input[type="text"]').filter(function(){
        return this.value.length > 0; 
    });

    return nonEmptyInputs.length > 0
});

var noOfNonEmptyTrs = trElements.length;   

$(document).ready(function() {
  $('button').click(function() {
    var trElements = $("#sample_table tr").filter(function() {
      //Get Non Empty inputs
      var nonEmptyInputs = $(this).find('input[type="text"]').filter(function() {
        return this.value.length > 0;
      });
      return nonEmptyInputs.length;
    });

    console.log(trElements.length);
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button">GET COUNT</button>
<table id="sample_table">
  <tbody>
    <tr>
      <td>
        <input type="text" value="">
      </td>
      <td>
        <input type="text" value="">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" value="">
      </td>
      <td>
        <input type="text" value="">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" value="">
      </td>
      <td>
        <input type="text" value="">
      </td>
    </tr>
    <tr>
      <td>
        <input type="text" value="">
      </td>
      <td>
        <input type="text" value="">
      </td>
    </tr>

  </tbody>
</table>