skip to Main Content

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.

2

Answers


  1. lots of ways to do this. here’s one approach to get you started

    function getTeams(){
       
        if (document.getElementById("sport").value == "soccer"){
            document.getElementById("soccer").style.display = 'block'
            document.getElementById("football").style.display = 'none'
        }else{
            document.getElementById("football").style.display = 'block'
            document.getElementById("soccer").style.display = 'none'
        }   
    }
    #football{
    display:none;
    }
    
    select{
       width:136px;
       text-align:center;
       }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <select id="sport"  onchange="getTeams()">
        <option>choose one</option>
        <option value="soccer" selected>Soccer</option>
        <option value="football" check>Football</option>
    </select>
    
    
    <br>
    
    <select id="soccer" >    
        <option>Manchester United</option>
        <option>Arsenal</option>
        <option>Milan</option>
    </select>
    
    <select id="football" >    
        <option>Steelers</option>
        <option>Giants</option>
        <option>Rams</option>
    </select>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search