This is the Main HTML page and the task was to create a dropdown list with student names and on click it should display their grade in an alert box. This is a project I'm giving a second look to improvr my grade and even after learning more, I'm still struggeling to get the final code. //HTML Task2
JavaScript
This is the creation of the map
let avrGrades = new Map()
avrGrades.set("Jade", 90)
avrGrades.set("Vel", 88)
avrGrades.set("Sky", 60)
avrGrades.set("Rian", 70)
avrGrades.set("Lizz", 90)
I ran a test loop here to see if the key vale pairs are being read.
for(let [key, value] of avrGrades){
console.log(key " " value)
}
Creating the Drop-down list with was quite simple to be honest.
for(let key of avrGrades.keys()){
let classList = document.getElementById("classList")
//Creating an id attribute
let att =document.createAttribute("id")
att.value = "option"
//Creating the option Element
let listItem = document.createElement("option")
//Adding the attribute to the option element
listItem.setAttributeNode(att)
listItem.innerHTML = key
classList.appendChild(listItem)
}
This sows the grade on click and here is were I am struggeling, i tried a few things but nothing works.
let show = document.getElementById("option")
show.addEventListener("click", function(){
for(let value of avrGrades.values()){
alert(value)
}
})
CodePudding user response:
I adjust your code like that:
const avrGrades = new Map();
const classList = document.getElementById("classList");
avrGrades.set("Jade", 90)
avrGrades.set("Vel", 88)
avrGrades.set("Sky", 60)
avrGrades.set("Rian", 70)
avrGrades.set("Lizz", 90)
for (const key of avrGrades.keys()) {
const listItem = document.createElement("option")
listItem.innerHTML = key
classList.appendChild(listItem)
}
classList.addEventListener("change", function() {
alert(avrGrades.get(classList.options[classList.selectedIndex].text))
})
<select id='classList'></select>
You try to use multiple same id
, but the ids must be unique, i simple use text of selected option for use .get and alert the value of grade
Reference:
CodePudding user response:
Your initial code should work if you specify a unique ID for each one of the option. At the moment you have
let att =document.createAttribute("id")
att.value = "option"
so each option has the same ID option
. Try using something unique like option-{key}
for each one, and set the click for each ID.
You can also remove this ID issue by targeting the elements using a class name instead of an ID
let shows = document.getElementsByClassName("option")
for (var i = 0; i < shows.length; i ) {
shows[i].addEventListener('click', [your function]);
}
assuming you give these elements a class with name option