简体   繁体   English

JavaScript:使用 onchange 使用下拉菜单过滤数据

[英]JavaScript: using onchange to filter data using a drop-down menu

My goal is filter data based on a user's selection in a drop-down menu.我的目标是根据用户在下拉菜单中的选择过滤数据。

SET UP设置

I have an array of objects named employees .我有一个名为employees的对象数组。 First, I sort by the salary attribute, then using another function manipulateData() , I filter by role attribute (which the user selects via a drop-down menu).首先,我按salary属性排序,然后使用另一个 function manipulateData() ,我按role属性(用户通过下拉菜单选择)进行过滤。

(notice in the HTML file that the manipulateData() function is called onchange ) (注意 HTML 文件中的manipulateData() function 被称为onchange

Here is my code:这是我的代码:

JavaScript: JavaScript:

let employees = [
    {
        id : 1,
        name : 'John Smith',
        role : 'Sales',
        salary : 100000
    },

    {
        id : 2,
        name : 'Mary Jones',
        role : 'Finance',
        salary : 78000,
    },

    {
        id : 3,
        name : 'Philip Lee',
        role : 'Finance',
        salary : 160000,
    },

    {
        id : 4,
        name : 'Susan Williams',
        role : 'Sales',
        salary : 225000,
    },

    {
        id : 5,
        name : 'Jason Alexander',
        role : 'Finance',
        salary : 90000,
    },

     {
        id : 6,
        name : 'Derek Sanders',
        role : 'Sales',
        salary : 140000,
    }

]

// ######################################### // #########################################

function filterData() {
    let allData = employees;

    let selectBox = document.getElementById("employee-role");
    let selectedValue = selectBox.options[selectBox.selectedIndex].value;

    // SORT SALARIES DESCENDING
    allData.sort(function (a, b) {
        return b.salary - a.salary;
    })

    console.log('Sorted Data', allData);

    // *** Here is where I'd like to invoke the dataManipulation() function to filter on only the user-selected roles

    // LIMIT TO ONLY 2 RECORDS
    let filteredData = allData.filter( (value, index) => {
        return (index < 2);
    });


    // RENDER THE CHART
    //renderChart(filteredData);
}

function manipulateData(filteredData) {
    return filteredData.filter(e => e.role === selectedValue)
}

HTML: HTML:

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="">
        <title>Example</title>

    </head>
    <body>

    <div class="container-fluid">

        <!-- header -->
        <div class="row justify-content-center">
            <div class="align-self-center">
                <h1>Example</h1>
            </div>
        </div>

        <!-- drop down menu -->
        <div class="row justify-content-center">
            <div class="align-self-center">
                <div class="user-control">
                    <div class="form-group">
                        <select id="employee-role" class="form-control" onchange="manipulateData()">
                            <option value="All">All Roles</option>
                            <option value="Sales">Sales</option>
                            <option value="Finance">Finance</option>
                        </select>
                    </div>
                </div>
            </div>
        </div>


        <!-- container of bar chart -->
        <div id="chart-area"></div>

    </div>
    </body>
</html>

Question: before I reduce the size of the data set to 2 records, how would I incorporate the manipulateData() function to grab only the role selected by the user via the drop-down menu?问题:在我将数据集的大小减少到 2 条记录之前,如何合并manipulateData() function 以仅获取用户通过下拉菜单选择的role

Thanks!谢谢! (JavaScript newbie here) (这里是 JavaScript 新手)

You can call manipulateData(allData, selectedValue) directly with your data set.您可以使用您的数据集直接调用manipulateData(allData, selectedValue) After this, you can remove onchange="manipulateData()" in your HTML.在此之后,您可以删除 HTML 中的onchange="manipulateData()"

 let employees = [{ id: 1, name: 'John Smith', role: 'Sales', salary: 100000 }, { id: 2, name: 'Mary Jones', role: 'Finance', salary: 78000, }, { id: 3, name: 'Philip Lee', role: 'Finance', salary: 160000, }, { id: 4, name: 'Susan Williams', role: 'Sales', salary: 225000, }, { id: 5, name: 'Jason Alexander', role: 'Finance', salary: 90000, }, { id: 6, name: 'Derek Sanders', role: 'Sales', salary: 140000, } ] function filterData() { let allData = employees; let selectBox = document.getElementById("employee-role"); let selectedValue = selectBox.options[selectBox.selectedIndex].value; // SORT SALARIES DESCENDING allData.sort(function(a, b) { return b.salary - a.salary; }) //call `manipulateData` and pass `allData` to the param for filtering let filteredData = manipulateData(allData, selectedValue) // LIMIT TO ONLY 2 RECORDS filteredData = filteredData.filter((value, index) => { return (index < 2); }); console.log(filteredData) // RENDER THE CHART //renderChart(filteredData); } function manipulateData(filteredData, selectedValue) { if(selectedValue === "All") { return //skip this logic, if the value is `All` } return filteredData.filter(e => e.role === selectedValue) }
 <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="description" content=""> <title>Example</title> </head> <body> <div class="container-fluid"> <!-- header --> <div class="row justify-content-center"> <div class="align-self-center"> <h1>Example</h1> </div> </div> <!-- drop down menu --> <div class="row justify-content-center"> <div class="align-self-center"> <div class="user-control"> <div class="form-group"> <select id="employee-role" class="form-control"> <option value="All">All Roles</option> <option value="Sales">Sales</option> <option value="Finance">Finance</option> </select> </div> </div> </div> </div> <button onclick="filterData()"> Check filtered data </button> <!-- container of bar chart --> <div id="chart-area"></div> </div> </body> </html>

Note that I added Check filtered data for the demo purpose.请注意,我出于演示目的添加了Check filtered data You can remove it and fill in other elements at your needs.您可以删除它并根据需要填写其他元素。

You want to modify the results down to the top two earners after the data is filtered.您希望在过滤数据后将结果修改为前两个收入者。

filteredByRole.slice(0, 2);

Details are commented in example细节在例子中注释

 const employees = [{ id: 1, name: 'John Smith', role: 'Sales', salary: 100000 }, { id: 2, name: 'Mary Jones', role: 'Finance', salary: 78000 }, { id: 3, name: 'Philip Lee', role: 'Finance', salary: 160000 }, { id: 4, name: 'Susan Williams', role: 'Sales', salary: 225000 }, { id: 5, name: 'Jason Alexander', role: 'Finance', salary: 90000 }, { id: 6, name: 'Derek Sanders', role: 'Sales', salary: 140000 }]; const data = employees.sort((a, b) => b.salary - a.salary); // Declare empty array outside of function let filteredByRole = []; // Register the <select> to the "change" event document.getElementById("employee-role").onchange = filterRole; // Event handler passes event object by default function filterRole(event) { // Assign the current value of <select> to a variable const role = this.value; /* If <select> current value is "All" then the array is the same... ...otherwise, filter each object (employee) and return only the properties that has a value that matches the current value of <select> */ if (role === "All") { filteredByRole = data.slice(0); } else { filteredByRole = data.filter(employee => employee.role === role); } // Log the filtered data console.log("Filtered by Role: "); console.log(JSON.stringify(filteredByRole)); console.log("|||||||||||||||||||||||||||||"); // Log the data for the top 2 earners console.log("Top two Earners by Role: "); console.log(JSON.stringify(filteredByRole.slice(0, 2))); console.log("|||||||||||||||||||||||||||||"); }
 <select id="employee-role" class="form-control"> <option value="All">All Roles</option> <option value="Sales">Sales</option> <option value="Finance">Finance</option> </select>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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