HTML / Javascript, таблица с несколькими фильтрами, еще раз (Vanilla JS) - PullRequest
2 голосов
/ 07 октября 2019

Хорошо, я создаю интерактивный стол, который начинает быть почти тем, к чему я стремлюсь, но не совсем. Расстроенно близко к этому. Я копал эту тему пару недель, но теперь мне кажется, что я зашел в тупик.

В принципе, единственное, чего мне сейчас не хватает, - это наложения фильтров. Эта тема также обсуждалась здесь довольно часто, но я, похоже, не нашел рабочего решения. у него также есть работающая система сортировки, которая имеет ту же проблему, но, вероятно, я могу с этим смириться.

В коде есть очень четкие проблемы (иначе {loadTableData (trailerTableData);} является наиболее очевиднойчто также приводит к тому, что флажки ведут себя больше как переключатели), и я думаю о нескольких вещах, но я не уверен, как их реализовать.

Создание новой таблицы после фильтрации не является хорошим решением, посколькуне работает со столбцом атрибутов, где вам нужно было бы видеть несколько атрибутов.

Циклический просмотр всех фильтров, вероятно, является одним из решений, но наличие локального контекста является препятствием.

В течение прошлой ночи я думал, что циклические чекбоксы также могут быть опцией, так как это не так важно, если это поле поиска не может быть наращиваемым. Последнее, вероятно, было бы самым простым решением ..?

//TABLE DATA
let trailerTableData = [
{pv:"ABC1234",side:"On", side2:"-", attribute:"2"},
{pv:"WRB2345",side:"-", side2:"On(1)", attribute:"3"},
{pv:"WRC4567",side:"-", side2:"-", attribute: "2"},
{pv:"RTD7890",side:"On(2)", side2: "On", attribute: "1"}
];

window.onload = () => {
    loadTableData(trailerTableData);
};

function loadTableData(trailerTableData) {
    let tableBody = document.getElementById ('trailerTableData');
    let dataHtml = '';

    for(let trailer of trailerTableData) {
    dataHtml += `<tr>

    <td>${trailer.pv}</td>
    <td>${trailer.side}</td>
    <td>${trailer.side2}</td>
    <td>${trailer.attribute}</td>
    </tr>`;
    }

    tableBody.innerHTML = dataHtml;
}

// INPUT SEARCH FOR PV
function filterTrailers() {
    let input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("inputTrailerSearch");
    filter = input.value.toUpperCase();
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td")[0];
        if (td) {
            txtValue = td.textContent || td.innerText;
            if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
            } else {
                tr[i].style.display = "none";
            }
        }
    }
}





// FUNCTION FOR CHECKBOX SIDE 1. PROBABLY NOT A GOOD SOLUTION BUT THIS ACTUALLY WORKS EXACTLY AS IT SHOULD, IF STACKING FILTERS WOULD NOT BE REQUIRED.
function filterSide1() {
    let input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("checkboxSide1Id");
    filter = input.value.toUpperCase();
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    if (input.checked != false) {
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[1];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
            } else {
                loadTableData(trailerTableData);
    }
}

// FUNCTION FOR CHECKBOX SIDE 2, SO IT'S THE SAME THAN WITH SIDE 1.
function filterSide2() {
    let input, filter, table, tr, td, i, txtValue;
    input = document.getElementById("checkboxSide2Id");
    filter = input.value.toUpperCase();
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    if (input.checked != false) {
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[2];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue.toUpperCase().indexOf(filter) > -1) {
                tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
            } else {
                loadTableData(trailerTableData);
    }
}





// THE REST 3 FUNCTIONS ARE FOR ATTIBUTE. ONLY CHANGE IS THAT THERE'S NO LOOP FOR FILTER. ONLY CHECKING IF VALUE IS 1. OR 2. OR 3.
function filterAttribute1() {
    let input, table, tr, td, i, txtValue;
    input = document.getElementById("checkboxAttribute1Id");
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    if (input.checked != false) {
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[3];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue == 1) {
                tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
            } else {
                loadTableData(trailerTableData);
    }
}

function filterAttribute2() {
    let input, table, tr, td, i, txtValue;
    input = document.getElementById("checkboxAttribute2Id");
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    if (input.checked != false) {
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[3];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue == 2) {
                tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
            } else {
                loadTableData(trailerTableData);
    }
}

function filterAttribute3() {
    let input, table, tr, td, i, txtValue;
    input = document.getElementById("checkboxAttribute3Id");
    table = document.getElementById("trailerTable");
    tr = table.getElementsByTagName("tr");

    if (input.checked != false) {
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td")[3];
            if (td) {
                txtValue = td.textContent || td.innerText;
                if (txtValue == 3) {
                tr[i].style.display = "";
                } else {
                    tr[i].style.display = "none";
                }
            }
        }
            } else {
                loadTableData(trailerTableData);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>TEST</title>
</head>

<body style="background-color: rgb(36, 36, 36)">
   
          <fieldset class="inputFieldset" style="width: 290px; background-color: rgb(255, 255, 0)"; >

        <div class="checkboxDiv">
            <input type="text" id="inputTrailerSearch" class="inputTrailerSearchField" maxlength="10" onkeyup="filterTrailers()" type="search" placeholder="search pv" onfocus="this.value=''">
        </div>
        
        <p></p>

        <div class="checkboxDiv">
            <input type="checkbox" name="side1" id="checkboxSide1Id" onchange="filterSide1()" class="checkboxSide1 checkbox">
            <label for="checkboxSideId" class="labels">SIDE 1</label>
        </div>

        <div class="checkboxDiv">
            <input type="checkbox" name="side2" id="checkboxSide2Id" onchange="filterSide2()" class="checkboxSide2 checkbox">
            <label for="checkboxSide2Id" class="labels">SIDE 2</label>   
        </div>

        <p></p>

        <div class="checkboxDiv">
                <input type="checkbox" name="attribute1" id="checkboxAttribute1Id" onchange="filterAttribute1()" class="checkboxAttribute1 checkbox">
                <label for="checkboxAttribute1Id" class="labels">ATTRIBUTE 1</label>   
            </div>
        
        
        <div class="checkboxDiv">
                <input type="checkbox" name="attribute2" id="checkboxAttribute2Id" onchange="filterAttribute2()" class="checkboxAttribute2 checkbox">
                <label for="checkboxAttribute2Id" class="labels">ATTRIBUTE  2</label>   
            </div>
        
        <div class="checkboxDiv">
                <input type="checkbox" name="attribute3" id="checkboxAttribute3Id" onchange="filterAttribute3()" class="checkboxAttribute3 checkbox">
                <label for="checkboxAttribute3Id" class="labels">ATTRIBUTE  3</label>   
            </div>



         </fieldset>
         <p></p>
         <fieldset class="inputFieldset" style="width: 290px; background-color: rgb(255, 255, 0)";>
            <table id="trailerTable" border="2" bordercolor="#000000" style="background-color: rgb(255, 255, 255)";>
                <thead id="tableHead">
                <tr>
                <th onclick="sortColumn('pv')">PV</th>
                <th onclick="sortColumn('side')">SIDE1</th>
                <th onclick="sortColumn('side2')">SIDE2</th>
                <th onclick="sortColumn('attribute')">ATTRIBUTE</th>
                </tr>
                </thead>
                <tbody id="trailerTableData"></tbody>
            </table>
        </fieldset>
        </div>
    </div>
</div>


    <script src="TRASH.JS" type="text/javascript"></script> 

</body>
</html>
...