Solution 1 :

First get all the select elements like,

const selects = document.querySelectorAll('select')

Then do forEach on all select box then make a separate addEventListener on each select like,

 selects.forEach(select => {
    select.addEventListener('change', () => {
      //Your logic here...

Then change for (var i = 0; i <= productHierarchy.length; i++) to for (var i = 0; i < productHierarchy.length; i++) .. Only give (< and not <=) as only two elements are there in productHierarchy..

Forked Codepen example here…

Problem :

I’ve created two select tags as “Material Group” which You can find in the link below:

Considering single text values in both select tags named “Material Group” I want to select the first option in Product Hierarchy. E.g:

Material Group:
“001 – SWAC” and “001 – SRAY”

First select in Product Hierachy should have options:
“ASH-09BIR” and “ASH-12BIR”

Please check some JS code:

var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");
var select3 = document.getElementById("select3");
var select4 = document.getElementById("select4");
var select5 = document.getElementById("select5");

var productHierarchy = ["ASH-09BIR", "ASH-12BIR"];

if (select1.options[select1.selectedIndex].text == "001 - SWAC" && select2.options[select2.selectedIndex].text == "001 - SRAY") {
  for (var i = 0; i <= productHierarchy.length; i++) {
    var opt = document.createElement("option");
    opt.value = opt.text = productHierarchy[i];

I’ve also tried “select3.appendChild(opt)”. However, it still does not work, I cannot display these two new options from an array declared.

Could You please advice? 😉


Comment posted by mplungjan

I would recommend you have “Please select” options or the user cannot trigger the change. Also I STRONGLY recommend to EITHER use jQuery OR DOM manipulation.

Comment posted by Lain

The adding of options works fine, yet you do trigger that code on loading the script and not on changing the options of the related selects.

Comment posted by Maniraj Murugan

@adan96ful, Please accept the answer if it helps you by clicking on the tick below vote option in the answer..