I have an array of objects, each with an age
and balance
property.
I have a form with a self-select field and a function to loop through and populate the self-select with all of the balances.age
values.
<form id="myForm">
<select id="selectAge">
<option>Age</option>
</select>
</form>
var balances = [
{
age: 23,
balance: 10000
},
{
age: 25,
balance: 24000
}
]
function getAge(){
for(var i = 0; i < balances.length; i++) {
var opt = balances[i].age;
var el = document.createElement("option");
el.text = opt;
el.value = opt;
select.add(el);
}
}
I'd like to use the selected age value and insert the corresponding balances of the array into some HTML below.
<h2>You should have $<span id="insertBalance"></span>.</h2>
I'm not getting anywhere with this and may have approached this wrong to begin with. How can I find the correct balance for each selected age and display it in my document?
You're pretty close. Add an event listener to the dropdown menu to listen for changes. When a change occurs, perform a linear search on the balances
array using find
to match the event.target.value
, which is the selected age.
Note that linear searching is slow, so if the search turns into a bottleneck, you may wish to transform the balances
array into an object or Map
with age->balance
pairs.
const balances = [
{
age: 23,
balance: 10000
},
{
age: 25,
balance: 24000
}
];
const selectEl = document.getElementById("select-age");
const balanceEl = document.getElementById("insert-balance");
for (const e of balances) {
const opt = document.createElement("option");
selectEl.appendChild(opt);
opt.text = e.age;
opt.value = e.age;
}
selectEl.addEventListener("change", event => {
const found = balances.find(e => e.age == event.target.value);
balanceEl.innerText = found ? found.balance : "";
});
<select id="select-age">
<option>Age</option>
</select>
<h2>You should have $<span id="insert-balance"></span>.</h2>