Filter Dropdown List Based on Another Dropdown List in JavaScript

Seeking expert guidance here! Currently working with Electron and have three key files that are involved in pulling data from a SQLite database (Data.js), organizing this data into arrays, and making it accessible through dropdown lists (Model.js and View.js). The challenge at hand is having the second dropdown list (for province names) filter according to the country selected in the first dropdown. Presently, both countries and provinces' full lists are displayed regardless of the initial selection.

Various attempts have been made, such as implementing an onchange event listener (yet unsuccessful due to certain complexities) or passing back the element value into the SQL query (but facing issues with value retention). Suggestions on the correct method to achieve this would be highly appreciated! Your insights are valuable!

Data.js:

function getCountries(done) {
// Function to pull country details from SQLite
}

function getProvinces(done) {
// Function to retrieve provinces along with their corresponding country details
}

Model.js:

function Countries(done) {
  // Access location values from data using specified function
}

function Provinces(done) {
// Retrieve all provinces available
}

View.js:

function viewCountries() {
// Display the list of countries on the page
}

function viewProvinces() {
// Show the provinces based on the selected country
}

HTML:

<p class="col-lg-2 col-md-4 col-sm-8 codes">COUNTRY</p>
// HTML code for displaying country information
<p class="col-lg-2 col-md-4 col-sm-8 codes">PROVINCE</p>
// HTML code for showing province details

Answer №1

You're heading in the right direction.

  1. To start, make sure to keep using the onchange event. It will detect when you change the country selection. When this occurs, it's time to update the province selection. Also, remember to reset the province selection whenever the country is changed to prevent any leftover data.

<select id="country-select" onchange="onCountryChanged()"></select>

function onCountryChanged() {
    resetProvincesSelect();
    viewProvinces($("#country-select").val());
}

function resetProvincesSelect() {
    var container = document.getElementById('province-select');
    $(container).empty();
}
  1. Revise your viewProvinces function to take a parameter, the country code, or ccode. Additionally, use the .filter() method to narrow down the provinces that belong to the selected country (ccode).
function viewProvinces(ccode) {
    var viewPro = Provinces(function(results) {
        // This code executes when Provinces() returns done(...); 
        var container = document.getElementById('province-select');
        var fragment = document.createDocumentFragment();
        results.filter(function(el) {
            return el.ccode === ccode;
        }).forEach(function(loc, index) {
            var opt = document.createElement('option');
            opt.textContent = loc.pname;
            opt.value = loc.pcode;
            fragment.appendChild(opt);
        });
        container.appendChild(fragment);
    });
}
  1. Make sure to include the ccode in the getProvinces() function.
{
    ccode: row.CountryCode,
    cname: row.CountryName,
    pname: row.ProvinceName,
    pcode: row.ProvinceCode
}
  1. You haven't specified where the main function is being called. Generally, it should be like this:

viewCountries();

You can also preload all provinces along with countries for faster selection without fetching data each time. This is a design choice. Consider abstracting the step of passing ccode to Provinces or getProvinces for better structure.

I hope this guidance helps you moving forward.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

AngularJS offers a variety of 'select all' checkboxes tailored for specific lists of checkboxes

Within my webpage, I have three different sets of checkboxes. Each set includes a "select all" checkbox. Instead of repeating code lines, I am implementing a single function with a parameter to select specific checkboxes within each set. $scope.sele ...

Error: Unable to access 'map' property of an undefined variable in ReactJS

Hello everyone, I'm struggling to understand why I keep getting this error when trying to retrieve data from the Covid19 API. It returns an object that contains a Countries array, but when I try to map over the Countries, I encounter an error. However ...

Implementing React Table selected rows from the parent component

I am currently facing an issue with my React Table component that has selectable rows. Although row selection is functioning properly and the parent component has access to information about the selected rows, I am struggling to set the selected rows from ...

jQuery Issue: Submission Count Doubling with Each POST Request

My current issue involves using jQuery to send data to a PHP file, but I've noticed that each time I submit the form, the data gets duplicated. Initially, it posts once when I press the submit button. However, upon returning to update the form and sub ...

Position the spinner in the center of the user's screen

I created my own spinner: '''' #spinner-bg-loading{ position: absolute; left: 50%; top: 25%; width: 80px; height: 80px; margin: -75px 0 0 -75px; border: 16px solid #FFFFFF; border-radius: 50%; border-top: 16px solid #1 ...

"Printed within the custom directive, the ng model value shows up as undefined

I am currently in the process of creating a custom directive that involves a simple template consisting of an input type textarea. I am assigning the ng-model to ngmodel and creating a link function where I am trying to capture the value of ngmodel. Howeve ...

Angular 12 - Encountering an issue with undefined properties when trying to access 'values'

Currently in the process of upgrading Angular Version from 8 to 12. Successfully made the upgrade from 8 to 11 without any issues. However, upon updating Angular to version 12, encountered an error stating "loadComponent TypeError: Cannot read propert ...

Struggling with sluggish performance during a loop while updating a MYSQL table

My current code is experiencing significant performance issues while using a WHILE LOOP to update table stock_figures with data from table product in the same database. The code iterates through each row in product, extracting the product_id and wholesale_ ...

Unable to execute SQL query statement

I am currently developing SQL queries within the Yii framework. Everything has been working smoothly up until I encountered an issue when comparing a variable to a string. Below is my function containing the problematic query: public function countCance ...

Transferring data from one page to another using form variables

Currently, I have an existing app at . The app is designed to function on a single page, but I have been requested to convert it into a multi-page flow. Transitioning data from one page to another has proven to be challenging for me as I am more of a hobby ...

Express in Node.js throwing error: 'Cannot GET /'

I recently created a contact us form on my website where users can input their email, name, and gender. The entered data is then stored in an output.txt file. Everything was working fine when I initially developed the website. However, today when I tried t ...

Assigning a value to an input field using jQuery

I'm facing an issue while trying to set the value for an input using jQuery. Essentially, when you click on a link, it redirects you to a different page with a form, and I am attempting to set the value of one of the inputs in that form. Unfortunately ...

The instance cannot be accessed by ES6 class methods

Having trouble accessing the this instance in one of my methods within a class that I created. In my router, I am calling the method like this: import Emails from '../controllers/emails' import router from 'express' .... route.post(&a ...

Create and adapt dynamic tiles to fit within the available width

I am looking to create a dynamic tile (div) that adjusts based on the number of users available, similar to how it works in Microsoft Teams meetings. For example, if there is only one user, the div should occupy the full screen. When there are two users ...

Navigating with jQuery Scrollbars

Looking to incorporate a bit of animation in jQuery, trying out the following line: window.parent.scroll(coord[0], coord[1]); The next block of code doesn't seem to be achieving what I had in mind. Do you have any suggestions? $(window.parent).anim ...

JavaScript hovering drop-down feature

Hi there, I'm just starting out with javascript and could use some help with a simple script. I have a shopping cart drop down that currently activates when clicked. However, I want it to fade in when hovered over instead. I've tried using .hove ...

What could be causing the presence of additional characters in the responseText received from the Servlet to JavaScript via Ajax?

I am currently involved in a project where I am attempting to retrieve the username from a session that was created using the code below: GetCurrentUserInfo.java package servlet; import java.io.IOException; import java.io.ObjectOutputStream; import java ...

Using Angular promises and the $http service

ng.module('app') .service('CardService', ['$http', CardService]) function CardService($http) { this.$http = $http; var self = this; $http.get('http://localhost:3000/db').success(function(data) { ...

Discovering the technique to dynamically load various content using jQuery in a div based on its

After discovering this code to extract information from the first div with an id of container (box4) and retrieve any new data from the URL, everything was functioning correctly. However, I encountered an issue when attempting to load box5 and rerun the co ...

Is there a way to convert a vector of character strings (each representing commands) into a function in R?

Trying to create a new function, known as the output-function, from input parameters is my current challenge. I have successfully generated the desired lines of code for the output-function as character strings and organized them into a vector to be execut ...