0

I've created two select tags as "Material Group" which You can find in the link below: [https://codepen.io/adan96/pen/ExaRgOe?editors=1010][1]

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];
    console.log(opt.value);
    select3.add(opt);
  }
}

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? ;)

2
  • 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. Commented Feb 12, 2020 at 7:56
  • 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. Commented Feb 12, 2020 at 8:02

1 Answer 1

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...

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

1 Comment

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

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.