append option to select menu?

前端 未结 4 1133
滥情空心
滥情空心 2020-11-29 06:10

Using Javascript how would I append an option to a HTML select menu?

e.g to this:


                        
    
提交评论

  • 2020-11-29 06:15

    You can also use insertAdjacentHTML function:

    const select = document.querySelector('select')
    const value = 'bmw'
    const label = 'BMW'
    
    select.insertAdjacentHTML('beforeend', `
      <option value="${value}">${label}</option>
    `)
    
    0 讨论(0)
  • 2020-11-29 06:30

    HTML

    <select id="mySelect">
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
    </select>
    

    JavaScript

     var mySelect = document.getElementById('mySelect'),
        newOption = document.createElement('option');
    
    newOption.value = 'bmw';
    
    // Not all browsers support textContent (W3C-compliant)
    // When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
    if (typeof newOption.textContent === 'undefined')
    {
        newOption.innerText = 'BMW';
    }
    else
    {
        newOption.textContent = 'BMW';
    }
    
    mySelect.appendChild(newOption);
    

    Demo →

    0 讨论(0)
  • 2020-11-29 06:34

    Something like this:

    var option = document.createElement("option");
    option.text = "Text";
    option.value = "myvalue";
    var select = document.getElementById("id-to-my-select-box");
    select.appendChild(option);
    
    0 讨论(0)
  • 提交回复
    热议问题