Home > Net >  How to populate a SELECT dropdown list with JavaScript array data?
How to populate a SELECT dropdown list with JavaScript array data?

Time:10-06

I'm new to HTML and javascript. I am trying to populate dropdown list with my data file and do a pie chart. My js data looks like below:

const businessData = 
  [ { '\ufeffbusiness_id': 'y2gFcAVBXmVxFXAugRe5ig'
    , name               : 'Scrumptious Crumpets'
    , address            : '7414 SE Milwaukie Ave'
    , city               : 'Portland'
    , state              : 'OR'
    , latitude           : '45.47107'
    , longitude          : '-122.64827'
    , stars              : '5'
    , review_count       : '23'
    , is_open            : '0'
    , category           : 'Coffee & Tea'
    , attr_key           : 'restaurantspricerange2'
    , attr_value         : '1'
    } 

Here's my dropdown looks like:

// render dropdown
const dropdownElement = document.getElementById("state-dropdown");

// states
let states = [ 
    { name: 'OREGON',        abbreviation: 'OR'},
    { name: 'FLORIDA',       abbreviation: 'FL'},
    { name: 'OHIO',          abbreviation: 'OH'},
    { name: 'MASSACHUSETTS', abbreviation: 'MA'},
    { name: 'TEXAS',         abbreviation: 'TX'},
    { name: 'COLORADO',      abbreviation: 'CO'},
    { name: 'GEORGIA',       abbreviation: 'GA'},
    { name: 'WASHINGTON',    abbreviation: 'WA'},
    { name: 'MINNESOTA',     abbreviation: 'MN'},
    ]

// create dropdown item
// <option value="CA">Open this select menu</option>
states.forEach(function(state) {

    //create the dropdown items
    const optionElement = document.createElement("option");
    //add dropdown value (we will use for code)
    optionElement.value = state.abbreviation
    //create the text that user can read
    const node = document.createTextNode(state.name);
    optionElement.appendChild(node);

    // append to the dropdown select
    dropdownElement.appendChild(optionElement)  
})

I want to create a drop down that would allow me to select data from multiple state and graph the data from that state. So far I've only been able get the graph to work by hard coding one state at a time.

How can I fetch the data to my dropdown so it does like... If select CA, show CA pie chart. If select OR, show OR pie chart, etc...

const californiaStars = businessData.filter(function (obj) {
    return obj.state === 'OR'; 
//Hard coding here in order to get my graph to work for state of OR only
})

let countOfFiveStars = 0
let countOfFourStars = 0
let countOfThreeStars = 0
let countOfTwoStars = 0
let countOfOneStar = 0

californiaStars.forEach(function(obj) {
    switch (obj.stars) {
        case "5":
            countOfFiveStars  ;
            break;
        case "4":
            countOfFourStars  ;
            break;
        case "3":
            countOfThreeStars  ;
            break;
        case "2":
            countOfTwoStars  ;
            break;
        case "1":
            countOfOneStar  ;
            break;
        default: break;
    }
})

console.log(californiaStars)
console.log(countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar)

// 3. put into graph (Pie Chart)
var options = {
    series: [
        countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar
    ],
    chart: {
    width: 700,
    type: 'pie',
  },
  labels: ['Five stars', 'Four stars', 'Three stars', 'Two stars', 'One star'],
  responsive: [{
    breakpoint: 480,
    options: {
      chart: {
        width: 200
      },
      legend: {
        position: 'bottom'
      }
    }
  }]
  };

  var chart = new ApexCharts(document.querySelector("#chart"), options);
  chart.render();

CodePudding user response:

for a start...

const
  dropdownElement = document.getElementById("state-dropdown")
, states = 
  [ { name: 'OREGON',        abbreviation: 'OR' } 
  , { name: 'FLORIDA',       abbreviation: 'FL' } 
  , { name: 'OHIO',          abbreviation: 'OH' } 
  , { name: 'MASSACHUSETTS', abbreviation: 'MA' } 
  , { name: 'TEXAS',         abbreviation: 'TX' } 
  , { name: 'COLORADO',      abbreviation: 'CO' } 
  , { name: 'GEORGIA',       abbreviation: 'GA' } 
  , { name: 'WASHINGTON',    abbreviation: 'WA' } 
  , { name: 'MINNESOTA',     abbreviation: 'MN' } 
  ]; 


states.forEach(({name,abbreviation})=>    // create dropdown items
  {
  dropdownElement.add( new Option(name,abbreviation))
  })
dropdownElement.onchange=()=>      // get item clicked when changed
  {
  console.log( dropdownElement.value )
  // ... 
  }
<select id="state-dropdown">
  <option value="" selected disabled>choose your state...</option>
</select>

CodePudding user response:

Complementing the answer, you can create a function that updates the chart as follows.

In your html

<select name="states" id="states" onchange="changeState()">
    <option value="OH">Ohio</option>
    <option value="FL">Florida</option>
    <option value="OR">Oregon</option>
    <option value="TX">Texas</option>
</select>
<div id="chart"></div>

Then in your script.js

// your data
let data = [{state: 'OR', stars: '5' ...}]

function changeState() {
    // Needed for you to update the chart
    let element = document.getElementById("chart")
    element.remove()
    element = document.createElement('div')
    element.setAttribute('id', 'chart')
    document.body.appendChild(element)

    let state = document.getElementById("states").value;
    // get data by state
    let filter_data = data.filter(d => d.state == state)
    let stars = getStars(filter_data)
    let options = getOptions(stars);

    let chart = new ApexCharts(document.querySelector("#chart"), options);
    chart.render();

}

function getStars(filter_data) {
    let countOfFiveStars = 0
    let countOfFourStars = 0
    let countOfThreeStars = 0
    let countOfTwoStars = 0
    let countOfOneStar = 0
    filter_data.forEach(data => {
        switch (data.stars) {
            case "5":
                countOfFiveStars  ;
                break;
            case "4":
                countOfFourStars  ;
                break;
            case "3":
                countOfThreeStars  ;
                break;
            case "2":
                countOfTwoStars  ;
                break;
            case "1":
                countOfOneStar  ;
                break;
            default: break;
        }
    });
    return [countOfFiveStars, countOfFourStars, countOfThreeStars, countOfTwoStars, countOfOneStar]
}

function getOptions(starts) {
    var options = {
      series: starts,
      chart: {
      width: 380,
      type: 'pie',
    },
    labels: ['Five stars', 'Four stars', 'Three stars', 'Two stars', 'One star'],
    responsive: [{
      breakpoint: 480,
      options: {
        chart: {
          width: 200
        },
        legend: {
          position: 'bottom'
        }
      }
    }]
}
    return options;
}
  • Related