Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JS Cascading dropdown showing index number instead of values

I have a cascading dropdown that has two select dropdowns. Let’s say, when I select Ariston in the first dropdown, it should show options "a, b, c, d" in the second dropdown. However, it is showing the index numbers of these options i.e. 0, 1, 2, and 3.

Please suggest what should I change in my JS code so that the second dropdown would show the related values.

Screenshot of the dropdown showing indexes

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var brandObject = {
      'Ariston': ["a","b","c","d"],
      'Airpop': ["a","b"],
      }

window.onload = function() {
  var brandSel = document.getElementById("brand");
  var modelSel = document.getElementById("model");

  for (var x in brandObject) {
    brandSel.options[brandSel.options.length] = new Option(x, x);
  }

  brandSel.onchange = function() {
    modelSel.length = 1;  // empty 2nd dropdown

    for (var y in brandObject[this.value]) {
      modelSel.options[modelSel.options.length] = new Option(y,y);   
    }
  }    
}
<select id="brand"></select>
<select id="model"></select>

>Solution :

Create the new Option using both the text and the array index:

new Option(
    brandObject[this.value][y], // text
    y                           // index
)
var brandObject = {
      'Ariston': ["a","b","c","d"],
      'Airpop': ["a","b"],
      }

window.onload = function() {
  var brandSel = document.getElementById("brand");
  var modelSel = document.getElementById("model");

  for (var x in brandObject) {
    brandSel.options[brandSel.options.length] = new Option(x, x);
  }

  brandSel.onchange = function() {
    modelSel.length = 1;  // empty 2nd dropdown

    for (var y in brandObject[this.value]) {
      modelSel.options[modelSel.options.length] = new Option(brandObject[this.value][y],y);   
    }
  }    
}
<select id="brand"></select>
<select id="model"></select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading