What\'s the easiest way to add an option
to a dropdown using jQuery?
Will this work?
$(\"#mySelect\").append(\'
$('#select_id').append($('<option>',{ value: v, text: t }));
You can add options dynamically into dropdown as shown in below example. Here in this example I have taken array data and binded those array value to dropdown as shown in output screenshot
Output:
var resultData=["Mumbai","Delhi","Chennai","Goa"]
$(document).ready(function(){
var myselect = $('<select>');
$.each(resultData, function(index, key) {
myselect.append( $('<option></option>').val(key).html(key) );
});
$('#selectCity').append(myselect.html());
});
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<select id="selectCity">
</select>
That works well.
If adding more than one option element, I'd recommend performing the append once as opposed to performing an append on each element.
for whatever reason doing $("#myselect").append(new Option("text", "text"));
isn't working for me in IE7+
I had to use $("#myselect").html("<option value='text'>text</option>");
This is just a quick points for best performance
always when you are dealing with many options, build a big string and then add it to the 'select' for best performance
f.g.
var $mySelect = $('#mySelect'); var str = '';
$.each(items, function (i, item) {
// IMPORTANT: no selectors inside the loop (for the best performance)
str += "<option value='" + item.value + "'> " + item.text + "</option>";
});
// you built a big string
$mySelect.html(str); // <-- here you add the big string with a lot of options into the selector.
$mySelect.multiSelect('refresh');
var str = "";
for(var i; i = 0; i < arr.length; i++){
str += "<option value='" + item[i].value + "'> " + item[i].text + "</option>";
}
$mySelect.html(str);
$mySelect.multiSelect('refresh');
Try
mySelect.innerHTML+= '<option value=1>My option</option>';
btn.onclick= _=> mySelect.innerHTML+= `<option selected>${+new Date}</option>`
<button id="btn">Add option</button>
<select id="mySelect"></select>