Updating a select dropdown's choices or values based on the selection of another select dropdown using JavaScript

I am working with two HTML select elements. Below is an example of the code:

<select class="select1" onchange='customJavascriptfuntion()'>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>


<select class="select2">
<option value='d'>d</option>
<option value='e'>e</option>
<option value='f'>f</option>

<option value='g'>g</option>
<option value='h'>h</option>
<option value='i'>i</option>
<option value='j'>j</option>
</select>

Currently, I am looking for a JavaScript function that will dynamically change the options in the second select based on the option selected in the first select. For instance, if "b" is selected in the first select, then the options in the second select should be "g,h,i,j". If "c" is selected, then the options should be "d,e,f", and if "a" is selected, then all options should be shown.

Answer №1

Here is an alternative approach using native JavaScript. This code snippet can also be easily converted to jQuery if desired.

function customImplementation(elm){
// get the select2 element (returns array so get the first item)
var select2 = document.getElementsByClassName('select2')[0];

// get the value of select 1
var currentValue = elm.value;

// create arrays for options
var optionB = ["g","h","i","j"]
var optionC = ["d","e","f"]
// combine both arrays for full list of options
var optionA = optionB.concat(optionC); 

// populate select 2 values based on select 1 value
if(currentValue === "a")
createOptions(optionA, select2)
else if(currentValue === "b")
createOptions(optionB, select2)
else if(currentValue === "c")
createOptions(optionC, select2)
}

// function to create options for select 2 (elm)
function createOptions(options, elm){
// reset current options
elm.innerHTML = "<option selected disabled>Select</option>";
// loop through each option and create <option> element
options.forEach(function(optionValue){
// create option element
var opt = document.createElement('option');
// set value
opt.value = optionValue;
// set inner html
opt.innerHTML = optionValue;
// add it to the select box
elm.add(opt)
})
}
<select class="select1" onchange='customImplementation(this)'>
  <option selected disabled>Select</option>
  <option value='a'>a</option>
  <option value='b'>b</option>
  <option value='c'>c</option>
</select>


<select class="select2">
  <option selected disabled>Select</option>
</select>

Answer №2

Implementing the functionality using pure javascript. By monitoring the onchange event, you can dynamically populate the second dropdown list (select2) based on the selected value in the first dropdown list (select1).

function customJavascriptFunction(obj) {
  var select2 = document.getElementsByClassName("select2")[0];
  select2.innerHTML = "";
  if (obj.value == "a") {
    var options = ['d', 'e', 'f', 'g', 'h', 'i'];
    options.forEach(option => {
      var opt = document.createElement('option');
      opt.value = option;
      opt.innerHTML = option;
      select2.appendChild(opt);
    });
  }
  if (obj.value == "c") {
    var options = ['d', 'e', 'f'];
    options.forEach(option => {
      var opt = document.createElement('option');
      opt.value = option;
      opt.innerHTML = option;
      select2.appendChild(opt);
    });
  }
  if (obj.value == "b") {
    var options = ['g', 'h', 'i'];
    options.forEach(option => {
      var opt = document.createElement('option');
      opt.value = option;
      opt.innerHTML = option;
      select2.appendChild(opt);
    });
  }
}
<select class="select1" onchange='customJavascriptFunction(this)'>
<option style="display:none">Select</option>
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
</select>

<select class="select2"></select>

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

In Laravel Blade, I am looking to display a Modal popup and dynamically pass data based on the user's ID

When a user clicks on the "View Details" Button, I need to display a popup modal with information specific to that user. The data for each user is stored in the $user variable. I would like to achieve the same functionality as demonstrated on this website ...

Leverage the values of object properties from a pair of JavaScript arrays containing objects

I am working with two arrays let arr1 = [{'id': 'ee', 'seat': '12'}, {'id': 'aa', 'seat': '8'} ] let arr2 = [ {'id': 's22', 'num': '&ap ...

How can I connect PHP table data with unique identifiers to JavaScript using arrays?

Allow me to clarify my question/task: 1) I currently have a PHP table that displays temperature data for a specific date and time using an API from a weather forecast. 2) The task at hand is to convert this table into a line graph using Javascript. 3) I a ...

Is it considered a bad practice to apply overflow: auto to all elements with the exception of html?

My approach to beginning a new design always involves overriding the default padding and margin set by the browser on all elements: * { margin: 0; padding: 0; } After coming across j08691's response regarding a margin collapse issue, I discovered th ...

Array of notifications in Vue framework

I am facing an issue with returning an array of notifications from my backend. I have a simple wizard form that displays success messages using Toastification. Here is how it looks: this.$toast({ component: ToastificationContent ...

React Component not retaining its value

I am currently facing an issue with a React component where I need to read a file from an Upload and pass the contents onto a child component for display. Although I can successfully read the file contents using FileReader and see the results in the cons ...

showing form validation tips alongside form fields

Currently, I have a JavaScript function that effectively displays form validation hints for input elements. However, I am facing an issue with extending this function to work with other form elements such as textarea, select box, and checkboxes. Can anyone ...

How should the folder structure be set up for dynamic nested routes in Next.js?

I've been reviewing the documentation for Next.js and believe I grasp the concept of dynamic routing using [slug].js, but I am facing difficulty understanding nested dynamic routes in terms of folder organization. If I intend to develop an applicatio ...

What is the appropriate Typescript return type to use for a $http request that only returns a successful response with no content?

I recently developed a Typescript service: class SettingsService implements ISettingsService { public info = {}; public backupInfo = {}; public userConfig = {}; public isLoaded = false; constructor( private $http: ng.IHttpSer ...

What is the best way to manage the delay that occurs when using the append() function?

I'm using jQuery to append an array to a div and I want to display a loading indicator while this process is happening. I added a callback function to my append logic, which works fine. However, the loader disappears before the array is fully rendered ...

Destroy Three.js Renderer

Is there an effective method to properly destroy a three js instance? I am encountering an issue where removing the canvas and re-adding it results in two renderers being created. Presently, my approach involves: Removing all event listeners Cancellin ...

Etiquette for the organization of jQuery functions through chaining and nesting

For developers familiar with jQuery, creating dynamic HTML easily can be done using the following method: var d = $('<div/>') .append('some text') .append( $('<ul/>').append( $('&l ...

What are the benefits of opting for $cacheFactory instead of the manual approach to fetching and storing data?

How does the method of manually maintaining an object variable as a cache compare to using $cacheFactory in Angular? When I say 'manually', I am referring to something like this- var cacheObj = {}; function setCache(data){ cacheObj = data ...

Steps for displaying an image link on an aspx webpage

Is it possible to have the full-size image open on http//example.com/image.aspx when the thumbnail is clicked, instead of http//example.com/images/image.jpeg? I am looking for a solution that does not require creating individual pages for each image or edi ...

Display Image After Uploading with AJAX

After spending nearly 3 hours working on implementing file uploads via AJAX, I have finally managed to get it up and running smoothly. Take a look at the code below: View <div class="form-horizontal"> <div class="form-group"> @Htm ...

ReactJS - When a click event is attached to a list of elements, it triggers the "click" event for each individual element in the list

I have a group of li elements under a ul element (as shown below), and when I click on any li element, I want it to add a class name to just that specific li element. However, currently when I click on one li element, the click event is triggered for all l ...

Are personalized URLs necessary for jump anchor links?

When utilizing 'Jump to' or 'Anchor' links to navigate to a different section of a webpage, should I include a canonical URL or use a 'no-follow' link for SEO optimization? Is it significant at all? And if so, which approach i ...

I am currently working on making my social items more responsive, however, I am encountering some issues. Any ideas or suggestions on how to resolve this

Find my resume project on GitHub at https://faizan-ul-hasnain.github.io/Resume-Project-/ and let me know how to improve it. Visit my resume project here ...

What benefits does utilizing unordered lists provide in navigation bars?

Throughout my research, I have come across numerous tutorials detailing the process of creating a navigation bar. They often begin by adding an unordered list and then proceed to remove the default styling such as bullet points and margins from both the ...

Combining Applet with Microsoft Access

This is a more specific version of my original inquiry. I have successfully created an applet that should interact with my MS Access database. It runs smoothly through a compiler, but when I embed the .class file in an html page and open it, the applet run ...