Issue
I've been working to attempt to append values to a dropdown via a function and nothing is being appended. The only thing showing is the "Dropdown Options". I even attempted to add a tag that would get updated when the function was called and that's not getting updated either so I can't tell if my function is being properly called.
I've currently just got it as
<select id="team" onchange="getTeams()">
<option>Dropdown Items</option>
</select>
let select = document.getElementById("team");
let elmnts = ["HTML", "CSS", "JS"];
function getTeams(){
for(let i = 0; i < elmnts.length; i++){
let optn = elmnts[i];
let el = document.createElement("option");
el.textContent = optn;
el.value = optn;
select.appendChild(el);
}
}
Not, I only took the snippets of the code, the function and variables are in the script portion and the html in the html section.
Solution
Just change onchange() to onfocus() and check the length of your select
let initialLength = document.getElementById("team").length
function getTeams(){
let select = document.getElementById("team");
let elmnts = ["HTML", "CSS", "JS"];
if (select.length == initialLength){
for(let i = 0; i < elmnts.length; i++){
let optn = elmnts[i];
let el = document.createElement("option");
el.textContent = optn;
el.value = optn;
select.appendChild(el);
}
}
}
<select id="team" onfocus="getTeams()">
<option>Dropdown Items</option>
</select>
Answered By - DCR
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.