简体   繁体   中英

Hide table row if every cell except first contains a space/is empty

I have a table that is filled from a CSV file into GridView. There is a header column and row. Some of the rows are empty except for the first column, which has a category. I am trying to create a condition in javascript where if the row is blank (except for the first cell), then the row is hidden.

$('tr:not(:first-child)').each(function () {

                let rowData = new Array();
                var q = 0;

                $(this).find('td:not(:first-child)').each(function () {

                    rowData[q++] = $(this).text();

                });

                let result = rowData.every(function (val) {

                    return val == " "

                });

                if (result == true) {
                    // hide row
                };
            });

When I debug the array, the value for rowData I want to return true is [, , , , , , ] and each value in the array is " " Any suggestions? Thanks.

Update:

This code works:

            $('tr:not(:first-child)').each(function () {
                let rowData = new Array();
                var q = 0;
                $(this).find('td:not(:first-child)').each(function () {
                    rowData[q++] = $(this).text();
                });
                let result = rowData.every(function (val) {
                    return String(val).trim() === ""
                });
                if (result == true) {
                    $(this).closest('tr').hide();
                };
            });

By checking with val == " " you only check if the string contains 1 empty string.

You can use jQuery.map() function to map the elements and use .get() function to get mapped values as array.

 $(document).ready(function() { let result = $('div.my-div:not(:first-of-type)').map(function() { return $(this).text() }).get().every(function(val) { return String(val).trim() === "" }); console.log(result) })
 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> <div class="my-div">1</div> <div class="my-div">&nbsp;</div> <div class="my-div"> </div> <div class="my-div"> </div> <div class="my-div"></div> <div class="my-div"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM