Search code examples
jqueryhtml-tableis-empty

Jquery find number of table rows with specific values in 2 columns


I have a table with 2 columns "id" (unique value) and "name". Using jQuery I would like to return the number (.length) of rows where the ID matches an array of ids (e.g. SR1, B1, B2) AND the value in the "name" field for those rows is empty.

So far I have:

var empty = $('[tabulator-field="name"]:empty').length;
var sr1 = $('.tabulator-row:nth-of-type(29) [tabulator-field="name"]:empty').length;
var sr2 = $('.tabulator-row:nth-of-type(30) [tabulator-field="name"]:empty').length;
var b1 = $('.tabulator-row:nth-of-type(7) [tabulator-field="name"]:empty').length;
var b2 = $('.tabulator-row:nth-of-type(8) [tabulator-field="name"]:empty').length;
var c10 = $('.tabulator-row:nth-of-type(27) [tabulator-field="name"]:empty').length;
var c11 = $('.tabulator-row:nth-of-type(28) [tabulator-field="name"]:empty').length;
var emptySR = sr1 + sr2 + b1 + b2 + c10 + c11;
var emptyBeds = empty - emptySR;

However, this seems like an inefficient way to calculate this and furthermore, selecting the rows I am interested in by their position in the table (rather than by their ID values) using :nth-of-type returns incorrect results if the table is sorted by a different field as the order of rows will change.

Please can anyone suggest a robust function for achieving what I need?


Solution

  • Use a selector to match the empty field, then use a filter function to test if the ID is in the array.

    var bedIds = ['SR1', 'SR2', 'B1', 'B2', 'C10', 'C11'];
    var emptyBeds = $('.tabulator-row:has([tabulator-field="name"]:empty) [tabulator-field="id"]').filter(function() {
        return bedIds.indexOf(this.textContent) != -1;
    }).length;