0

I've created dynamic dropdown list and I want to obtain values from selected option. Dynamic dropdown works fine but I have struggle with taking values from selected option. For example I want to take value of avgDamage from selected object tpPrototype.

Need some help here

HTML:

<form name="myform" id="myForm">
    <p>tank 1</p>
    <div class="select">
        <select classname="optone" id="tankSel" size="1">
            <option value="" selected="selected">Tank Nation</option>
        </select>
    </div>
    <div class="select">
        <select name="opttwo" id="typeSel" size="1">
            <option value="" selected="selected">Tank Type</option>
        </select>
    </div>
    <div class="select">
        <select name="optthree" id="nameSel" size="1">
            <option value="" selected="selected">Tank Name</option>
        </select>
    </div>
</form>

JavaScript:

const tpPrototype = {
    name: "50TP prototyp",
    avgDamage: 440,
    healthPool: 1500,
    reloadTime: 13.62,
},
tpMarkowskiego = {
    name: "53TP prototyp",
    avgDamage: 420,
    healthPool: 1450,
    reloadTime: 12.18,
},
proggettoM35 = {
    name: "Progetto M35 mod.46",
    avgDamage: 240,
    healthPool: 1400,
    reloadTime: 1,
},

window.onload = function () {
let tankSel = document.getElementById("tankSel");
    typeSel = document.getElementById("typeSel");
    nameSel = document.getElementById("nameSel");

for (let tank in tankObject) {
    tankSel.options[tankSel.options.length] = new Option(tank, tank);
}
tankSel.onchange = function () {
    typeSel.length = 1;
    nameSel.length = 1;
    if (this.selectedIndex < 1) return;
    for (let type in tankObject[this.value]) {
        typeSel.options[typeSel.options.length] = new Option(type, type);
    }
};
tankSel.onchange();
typeSel.onchange = function () {
    nameSel.length = 1;
    if (this.selectedIndex < 1) return;
    let names = tankObject[tankSel.value][this.value];
    for (let i = 0; i < names.length; i++) {
        nameSel.options[nameSel.options.length] = new Option(names[i], names[i]);
    }
};
Hossein Golshani
  • 1,847
  • 5
  • 16
  • 27
Lucius
  • 1
  • 1

1 Answers1

0

This looks like a duplicate of question 1085801

Basically, once you have the selection object, you access the "value" attribute through:

var selectedValue = selectionObject.options[index].value;

or you can access the actual text, such as "Tank Type" in your initial HTML as:

var selectedText = selectionObject.options[index].text;

Once you have this, you should just be able to use that value/text to access your "tankObject" property:

var selectedAvgDamage = tpPrototype[selectedText];
L M
  • 36
  • 3