I was tasked to use a map to store the names of 5 students with their corresponding average grade. I have initialised this map with fictitious hardcoded names and grades as follows:
const avgGrade = new Map();
avgGrade.set('Kyle', '82%');
avgGrade.set('Sarah', '50%');
avgGrade.set('Skye', '96%');
avgGrade.set('Taylor', '75%');
avgGrade.set('Bantu', '98%');
My goal is to write the JavaScript to display the name of each student in a drop-down menu. When the student’s name is selected from the drop-down menu, the student’s grade should be displayed using an alert. These are the hints I was given (Hint: Remember that you can use the value and innerHTML attributes of an element.)
I tried doing this, but there is something I'm not getting right. can someone please tell me where I'm going wrong. Here's my code:
//dropdown menu using a for loop
let dropdown = document.querySelector('#dropdown');
for (i=0; i<avgGrade.length; i++){
let option = document.createElement('option');
option.innerHTML = avgGrade.keys();
dropdown.appendChild(option);
}
//also,I to just alert like this:
function studentGrades()//called the function in select tag on the DOM using the onchange event
{
alert( Select.options[selectedIndex].value + ' average grade is ' + avgGrade.values[i]);
}
You will have to make sure you are iterating Map correctly. You can use forEach() for that. To insert your options please give both text and value.
Variables like Select , i, selectedIndex are not defined in your code.
To get the values from Map, please use standard Map methods like get().
const avgGrade = new Map();
avgGrade.set('Kyle', '82%');
avgGrade.set('Sarah', '50%');
avgGrade.set('Skye', '96%');
avgGrade.set('Taylor', '75%');
avgGrade.set('Bantu', '98%');
let dropdown = document.querySelector('#dropdown');
avgGrade.forEach((val, key) => {
let option = document.createElement('option');
option.text = key;
option.value = key;
dropdown.appendChild(option);
});
//also,I to just alert like this:
function studentGrades(select) {
//called the function in select tag on the DOM using the onchange event
alert(select.value + ' average grade is ' + avgGrade.get(select.value));
}
<select id="dropdown" onchange="studentGrades(this)">
</select>
I took the liberty of passing this as an argument on the onChange. You might be doing it some other way.