How to Add Options to Select Input with jQuery
In this tutorial, we will go through some of the different ways of adding a new option element to a select input field.
Add Option to Select Input with the jQuery append() Function
The first approach is to use the jQuery append()
function to add a new option after the existing options.
<select id="selection">
<option value="2">An option</option>
</select>
$('#selection').append($('<option>', {
value: 1,
text: 'My option'
}));
<select id="selection">
<option value="2">An option</option>
<option value="1">My option</option>
</select>
Add Option Before All Other Options in Select Input
To add an option before all the existing options in a select input, use the jQuery prepend function like this:
$('#selection').prepend($('<option>', {
value: 1,
text: 'My option'
}));
<select id="selection">
<option value="1">My option</option>
<option value="2">An option</option>
</select>
If you don't like using a dictionary to add the value and text of the option element, use val()
and text()
like this:
$('#selection').append($('<option>').val(1).text('My option'));