-1

I need to create two dropdown menus on a webpage - (the second dropdown menu is dependent on the first dropdown menu) - and populate both the menus with records from two different columns of a .csv file.

I'm able to read the csv file using NodeJS and get both the required columns into two different arrays as below:

uniqueCountryName
[
 'Italy',
 'Spain',
 'France',
 'England'
]
uniqueCityName
[
 'Paris',
 'Milan',
 'Marseilles',
 'Venice'
 'London',
 'Rome',
 'Berlin',
 'Madrid',
 'Barcelona' 
]

This is the nodeJS code I've used so far:

const csv = require('csv-parser');
const fs = require('fs');
const results = [];
const CountryName = [];
const CityName = [];

fs.createReadStream('C:/Users/learningsql/Desktop/project.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
    var CountryName = []
    for (var item in results) {
        CountryName.push(results[item]["CountryName"])
    }
    /* console.log(CountryName) */

    const uniqueCountryName = Array.from(new Set(CountryName));
    console.log("uniqueCountryName")
    console.log(uniqueCountryName)
});

fs.createReadStream('C:/Users/learningsql/Desktop/project.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
    for (var item in results) {
        CityName.push(results[item]["CityName"])
    }
    /* console.log(CityName) */

    const uniqueCityName = Array.from(new Set(CityName));
    console.log("uniqueCityName")
    console.log(uniqueCityName)
});

Now I need to do two things: First I need to populate these two different arrays in two different dropdown menus on a webpage. The CountryName should go into the first dropdown menu and the CityName should go into the second dropdown menu. It's my understanding that browser can't read the output from the terminal, so we need to set up a server using Express.JS. How can I do this?

Second, as I already mentioned that the second dropdown records should be dependent on the first one, how can we map/link both the arrays? For example, when I select Italy in the first dropdown menu, only Italian cities (Milan, Venice, Rome etc) should show up in the second dropdown menu. If I select Spain, only Spanish cities should show up in the dropdown menu (Madrid, Barcelona etc).

For reference, the dropdown menu should be something like this

I'm a total newbie to NodeJS and any help is appreciated. Thanks.

0

1 Answer 1

0

You have asked two questions here. One is how to use express. The other is how to implement dependent dropdowns. Perhaps these should be two different questions but let me tackle each one here. First, how do we use express (which is a web server written in node)

1. How to use Express

  1. Install express in a directory of your choosing (see link for details)
  2. $ npm install express --save
  3. Create a new javascript file
  4. Use the code below
    var express = require('express');
    var app = express();   
    app.get('/', function (req, res) {
      res.send("<h1>hello world</h1>");
    });    
    app.listen(8080, function () {
      console.log('Example app listening on port 8080!');
      //call this app from localhost://8080 
    });

This is a simple "hello world". I've explained this in detail in this blog. If you want to use an html file instead of simple html code, use the following:

var http = require('http');
var fs = require('fs');
http.createServer(function (req, res) {
  fs.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    return res.end();
  });
}).listen(8080);

Note that you will need to use npm or other package to install express, http and fs. Your html code will be in index.html.

Your second question is on how to use dependent dropdowns.

2. Dependent dropdowns

For dependent dropdowns, you are working purely on the client side. So vanilla javascript code will work. For instance, you can use jquery or other useful libraries.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<!-- optionally if you need translation for your language then include locale file as mentioned below -->
<script src="path/to/js/locales/<lang>.js"></script>
<h1>Dependent Dropdown</h1>

<form name="myform" id="myForm">
    <select name="optone" id="continentSel" size="1">
        <option value="" selected="selected">Select continent</option>
    </select>
    <br>
    <br>
    <select name="opttwo" id="countrySel" size="1">
        <option value="" selected="selected">Please select continent first</option>
    </select>
    <br>
    <br>
    <select name="optthree" id="citySel" size="1">
        <option value="" selected="selected">Please select state first </option>
    </select>
</form>
<hr/>


<script>
var stateObject = {
  "Europe": {
          "France": ["Paris", "Lyon"],
          "UK": ["London", "Birmingham"]
      },
      "Africa": {
          "Senegal": ["Dakar", "Louga"],
          "South Africa": ["Cape Town", "Pretoria"]
      }
}
window.onload = function () {
    var continentSel = document.getElementById("continentSel"),
        countrySel = document.getElementById("countrySel"),
        citySel = document.getElementById("citySel");
    for (var item in stateObject) {
        continentSel.options[continentSel.options.length] = new Option(item, item);
    }
    continentSel.onchange = function () {
        countrySel.length = 1; // remove all options bar first
        citySel.length = 1; // remove all options bar first
        if (this.selectedIndex < 1) return; // done
        for (var item in stateObject[this.value]) {
            countrySel.options[countrySel.options.length] = new Option(item, item);
        }
    }
    continentSel.onchange(); // reset in case page is reloaded
    countrySel.onchange = function () {
        citySel.length = 1; // remove all options bar first
        if (this.selectedIndex < 1) return; // done
        var cities = stateObject[continentSel.value][this.value];
        for (var i = 0; i < cities.length; i++) {
            citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
        }
    }
}
</script>

Finally see the full working code here

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I've made little changes and I'm able to get it working.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.