Using Javascript how would I append an option to a HTML select menu?
e.g to this:
$(document).ready(function(){
$('#mySelect').append("<option>BMW</option>")
})
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>
`)
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
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 →
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);