I have a function that populates a list of option elements into a select element.
function createOptionElements(){
const select = document.querySelector('select');
for(let i=1;i<11;i++){
const option = document.createElement('option');
option.textContent = i;
select.appendChild(option);
}
}
When I select the option value 3 from the select I would like console.log(option.textContent) to output true.
function outputOptionTextContent(){
const option = document.querySelector('option');
if (option.textContent === "3"){
console.log(true);
}
else {
console.log(false);
}
}
When I simply call console.log(option.textContent) I only ever get the first value in the list, which is 1, even If I select a different value.
The reason I am attempting to do this is, I am calling an HTTP GET request on JSON data, the data has name properties, the name properties will be added to the select as options, & I would like to to call a function when a specific name is clicked, so I was thinking of adding a function that looked for the value of textContent and then compared the textContent value to the name in the JSON data, if they match, invoke the function.
The reason behind could be the fact that textContent is not an standard attribute the standard attribute is value also is better if you use the method built in to do it
option.setAttribute(“value”, variableWithValue);
And yes you guessed it correctly if there is a setAttribute there is also a getAttribute
option.getAttribute(“value”);
So the end result should look like this
window.addEventListener('DOMContentLoaded', (event) => {
console.log('DOM fully loaded and parsed');
const select = document.querySelector('select');
for(let i=1;i<11;i++){
const option = document.createElement('option');
option.setAttribute(“value”,i);
select.appendChild(option);
}
/// add the select to the document
document.body.appendChild(select);
select.addEventListener("change", (e) => {
const optionSelected = e.target.value;
})
});