In a HTML list, I have made 3 options, those should be all linked to an object. This object houses different values, from which I want to calculate a sum in a further function, based on the selection. I have been trying to figure out the easiest way to approach this js problem, but I cannot figure it out. Is there any good way to solve this issue? Thanks in advance!
const lxaib = {
bem: 647,
bemcg: 2.112,
crewcg: 2.05,
paxcg: 2.993,
bagcg: 3.627,
fuelcg: 2.413,
}
// Just an example of working with the first object that should be related to the first list value
function getselectvalue() {
var selectedvalue = document.getElementById("list").value;
document.getElementById("test").innerHTML = selectedvalue;
}
function zfm() {
bem = selectedvalue.bem; // I need to get the variable stored in the object based on the user selection here ...
crew = parseFloat(document.getElementById("crew").value);
pax = parseFloat(document.getElementById("pax").value);
bag = parseFloat(document.getElementById("baggage").value);
zfm = bem + crew + pax + bag;
document.getElementById("zfm").innerHTML = zfm;
}
<select name="airplanes" id="list" onchange="getselectvalue();">
<option value="lxaib">LXAIB</option>
<option value="lxaig">LXAIG</option>
<option value="lxaif">LXAIF</option>
</select>
<br>
<input type="number" name="crew" id="crew" placeholder="crew">
<br>
<input type="number" name=" pax" id="pax" placeholder="pax">
<br>
<input type="number" name="baggage" id="baggage" placeholder="baggage">
<br>
<span id="test"></span>
<br>
<span id="zfm"></span>
<br>
<button onclick="zfm();">Calculate ZFM</button>
3
Answers
You can wrap all the inputs and the button around a form element and then listen to it’s submit event to extract all the values. Here’s the example:
Your data object will need to be in an object with the keys matching that of the select.
Then you get the object via bracket notation.
selected = data[selectedvalue];
Also, the selected variable will need to be declared outside of the function so that it can be access within the other functions.
Also it is best to use event listeners not inline event handlers (like onclick, onchange etc)
my advice: take an interest in the online documentation
https://developer.mozilla.org/en-US/docs/Learn/Forms/Your_first_form