首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JavaScript:使用onchange来使用下拉菜单过滤数据。

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

Stack Overflow用户
提问于 2022-09-13 02:15:28
回答 2查看 76关注 0票数 2

我的目标是在下拉菜单中根据用户的选择筛选数据.

设置

我有一个名为employees的对象数组。首先,我根据salary属性进行排序,然后使用另一个函数manipulateData()根据role属性进行筛选(用户通过下拉菜单选择该属性)。

manipulateData() (注意,在HTML文件中,函数称为)。

这是我的代码:

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,
    }

]

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

代码语言:javascript
复制
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:

代码语言:javascript
复制
<!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>

问题:在我将数据集的大小缩小为2条记录之前,如何通过下拉菜单将manipulateData()函数合并为只获取用户选择的role

谢谢!(这里是JavaScript新手)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-09-13 02:30:28

您可以使用数据集直接调用manipulateData(allData, selectedValue)。在此之后,您可以在HTML中删除onchange="manipulateData()"

代码语言: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;
  })

  //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 filteredData;//skip this logic, if the value is `All`
  }

  return filteredData.filter(e => e.role === selectedValue)
}
代码语言:javascript
复制
<!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>

请注意,我为演示目的添加了Check filtered data。您可以删除它,并在需要时填写其他元素。

票数 1
EN

Stack Overflow用户

发布于 2022-09-13 03:16:06

您希望将结果修改到前两位员工(),在之后,对数据进行过滤。

代码语言:javascript
复制
filteredByRole.slice(0, 2);

详细信息在示例中有注释

代码语言:javascript
复制
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("|||||||||||||||||||||||||||||");
}
代码语言:javascript
复制
<select id="employee-role" class="form-control">
  <option value="All">All Roles</option>
  <option value="Sales">Sales</option>
  <option value="Finance">Finance</option>
</select>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73696892

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档