简体   繁体   中英

How to filter Table row with multiple condition .ie on checkbox selection show respected row. each checkbox represent Column and row value

I have a table with some dynamic data, and columns as Name,Location, Salary. Problem i am facing in Step 2 ie multiple condition check. Heres the step by step code.

JS Fiddle Demo

Step 1-

Auto generate Filters ie dynamically add Checkboxes, depend on table row values

 autoFilterItem("filterDiv"); 

Above function generate dynamic checkboxes, logic is it loop over table, read values row by row and return unique value array and generate checkbox respectively, currently am doing for 2 cols having class loc,sal.

Step 2-

Checkbox change event, depend on status (checked/unchekced) table rows will be hide/show .

The problem i am facing is, if user checked 100 ( class as sal) , and Kerala ( class as loc) is unchecked then row having kerala should be hide.

For hide and show am adding/removing class .hideRow

///STEP TWO 
// On any checkbox clicked returns   desired out
$("body").on('change', '.chk', function () {
    var arrObj = [],
        arrCheckedValueCLass = [];
    var objCheckedData = {};
    $("#filterDiv .chk").each(function (index, val) {
        var sf = $(this);
        if (sf.is(":checked")) {
            var sf = $(this);
            arrObj.push({
                dataValue: $(sf).attr('data-value'),
                dataClass: $(sf).attr('data-class')
            });
        }
    });

    var self = $(this);
    var getClassName = self.attr("data-class");
    var matchTextValue = $.trim(self.attr("data-value"));
    if (self.is(":checked")) {
        if (matchTextValue == "All") {
            $(".chk").prop('checked', true);
        }
        $("." + getClassName).each(function () {
            var innerSelf = $(this);
            var gVal = $.trim(innerSelf.html());
            if (matchTextValue == "All") {
                innerSelf.closest("tr").removeClass("hideRow");
            } else {
                if (matchTextValue === gVal) {
                    console.log("checked and matchTextValue");
                    var i = 0,
                        lg = arrObj.length;
                    var flagSet = false;
                    for (i; i < lg; ++i) {
                        var objValue = arrObj[i].dataValue;
                        var objClass = arrObj[i].dataClass;
                        if (getClassName != objClass) {
                            var prevDataCheck = $.trim(innerSelf.closest("tr").find("." + objClass).html());
                            if (prevDataCheck == objValue) {
                                flagSet = true;
                                return true;
                            }
                        }
                    }
                    if (!flagSet) {
                        innerSelf.closest("tr").removeClass("hideRow");
                        innerSelf.closest("tr").addClass(getClassName + "_X");
                    }
                }
            }
        });
    } else {

        if (matchTextValue == "All") {
            $(".chk").prop('checked', false);
        }

        $("." + getClassName).each(function () {
            var innerSelf = $(this);
            var gVal = $.trim(innerSelf.html());
            if (matchTextValue === gVal) {
                innerSelf.closest("tr").addClass("hideRow");
                innerSelf.closest("tr").removeClass(getClassName + "_X");
            }
        });
    }
});

<div id="filterDiv"></div>
<button>Click</button>
<br>
<div id="tableContainer">
    <table id="myTable">
        <thead>
            <tr>
                <th data-name='name'>Name</th>
                <th data-loc='Location'>Location</th>
                <th data-sal='salary'>Salary</th>
                <th data-sts='Active'>Active</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td class="name">James</td>
                <td class="loc">Mumbai</td>
                <td class="sal">500</td>
                <td class="sts">Yes</td>
            </tr>
            <tr>
                <td class="name">Joseph</td>
                <td class="loc">Kerala</td>
                <td class="sal">100</td>
                <td class="sts">No</td>
            </tr>
            <tr>
                <td class="name">Jack</td>
                <td class="loc">Delhi</td>
                <td class="sal">500</td>
                <td class="sts">Yes</td>
            </tr>
            <tr>
                <td class="name">Andrea</td>
                <td class="loc">Mumbai</td>
                <td class="sal">1000</td>
                <td class="sts">No</td>
            </tr>
            <tr>
                <td class="name">David</td>
                <td class="loc">Delhi</td>
                <td class="sal">100</td>
                <td class="sts">No</td>
            </tr>
            <tr>
                <td class="name">David</td>
                <td class="loc">Delhi</td>
                <td class="sal">99900</td>
                <td class="sts">No</td>
            </tr>
        </tbody>
    </table>
</div>

I have created the fiddle from the things that you noted and able to produce the result( that is, if user checked 100 ( class as sal), and Kerala ( class as loc) is unchecked then row having kerala should be hide.)

I do not how efficient the solution is.There may be more efficient way to acheive that but anyway below is the js code.

$(document).ready(function () {


        //STEP ONE STARTS
        // This function generate checkbox from table data, which will be used for filteration   
        autoFilterItem("filterDiv");

        function autoFilterItem(idOfHolderDiv) {
            $("#" + idOfHolderDiv).empty();
            var arr1 = [];
            $(".sal").each(function () {
                arr1.push($.trim($(this).html()));
            });
            var arrNew = unique(arr1).sort(function (a, b) {
                return a - b
            });
            $.each(arrNew, function (i, val) {
                $("<input/>", {
                    "type": "checkbox",
                    "class": "chk",
                    "data-class": "sal",
                    "data-value": val,
                    "id": "chk" + val,
                    "checked": "checked"
                }).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
            });

            $("#" + idOfHolderDiv).append("<hr>");
            var arr2 = [];
            $(".loc").each(function () {
                arr2.push($.trim($(this).html()));
            });
            var arr2New = unique(arr2).sort();

            $.each(arr2New, function (i, val) {
                $("<input/>", {
                    "type": "checkbox",
                    "class": "chk",
                    "data-class": "loc",
                    "data-value": val,
                    "id": "chk" + val,
                    "checked": "checked"
                }).appendTo("#" + idOfHolderDiv).wrap("<div></div>").after(val);
            });
            $("#" + idOfHolderDiv).append("<hr>");
            function unique(array) {
                return $.grep(array, function (el, index) {
                    return index == $.inArray(el, array);
                });
            }
        }
        // STEP ONE ENDS



        ///STEP TWO 
        // On any checkbox clicked returns   desired out

        var selectedSalaryArr = [];
        var selectedLocationArr = [];

        $("body").on('change', '.chk', function () {
            var selectedVal = $(this).attr('data-value');
            $('#filterDiv div').each(function () {
                var checkedval = $(this).find('input.chk').attr('data-value');
                var isChecked = $(this).find('input.chk').is(':checked');
                var dataClass = $(this).find('input.chk').attr('data-class');
                if (selectedVal === checkedval) {
                    if (dataClass === 'sal') {
                        var isExists = $.inArray(checkedval, selectedSalaryArr);
                        if (isExists === -1) {
                            selectedSalaryArr.push(checkedval);
                        } else {
                            selectedSalaryArr.splice($.inArray(checkedval, selectedSalaryArr), 1);
                        }
                    } else {
                        var isExists = $.inArray(checkedval, selectedLocationArr);
                        if (isExists === -1) {
                            selectedLocationArr.push(checkedval);
                        } else {
                            selectedLocationArr.splice($.inArray(checkedval, selectedLocationArr), 1);
                        }
                    }
                }
            });

            $('#myTable tbody tr').each(function () {
                var currentSalary = $(this).find('.sal').text();
                var currentLocation = $(this).find('.loc').text();

                var matchedSalaryValueExists = $.inArray(currentSalary, selectedSalaryArr);
                var matchedLocationValueExists = $.inArray(currentLocation, selectedLocationArr);

                if (selectedSalaryArr.length > 0 && selectedLocationArr.length > 0) {
                    if (matchedSalaryValueExists !== -1 && matchedLocationValueExists !== -1) {
                        if (!($(this).hasClass('hiderow'))) {
                            $(this).addClass('hiderow');
                        }
                    } else {
                        if ($(this).hasClass('hiderow')) {
                            $(this).removeClass('hiderow');
                            $(this).show();
                        }
                    }
                }
                else {
                    if (matchedSalaryValueExists !== -1 || matchedLocationValueExists !== -1) {
                        if (!($(this).hasClass('hiderow'))) {
                            $(this).addClass('hiderow');
                        }
                    } else {
                        if ($(this).hasClass('hiderow')) {
                            $(this).removeClass('hiderow');
                            $(this).show();
                        }
                    }
                }
            });
            $('#myTable tbody tr.hiderow').hide();
        });
    });

Below is the jsfiddle link:

https://jsfiddle.net/shrawanlakhe/v8gyde77/

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