Home > Mobile >  JS Cascading dropdown showing index number instead of values
JS Cascading dropdown showing index number instead of values

Time:06-08

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

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>

CodePudding user response:

you need to use the index that you got on the y variable to retrieve the value from your array brandObject[this.value][y]

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], brandObject[this.value][y]);
    }
  }
}
<select id="brand">

</select>
<select id="model">

</select>

  • Related