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>
This question is related to
javascript
html
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);
$(document).ready(function(){
$('#mySelect').append("<option>BMW</option>")
})
Source: Stackoverflow.com