41

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

e.g to this:

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

http://jsfiddle.net/SSwhr/

Matt Ball
  • 344,413
  • 96
  • 627
  • 693
Skizit
  • 40,756
  • 89
  • 203
  • 267

4 Answers4

89

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);
Marcus Frödin
  • 11,942
  • 2
  • 24
  • 16
  • Interesting, `option.text` definitely works, but I can't find any documentation on it (W3C, MDC, quirksmode, etc.). – Matt Ball Mar 03 '11 at 15:53
17
$(document).ready(function(){

    $('#mySelect').append("<option>BMW</option>")

})
Ryan Miller
  • 381
  • 1
  • 12
  • 2
    Doh! I *thought* the original question was tagged with jQuery. But, also, as the only starting point was an html snippet, why not jQuery? – Ryan Miller Mar 03 '11 at 15:36
8

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 →

Matt Ball
  • 344,413
  • 96
  • 627
  • 693
5

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>
`)
imkost
  • 7,803
  • 6
  • 28
  • 47