Browse - Programming Tips - How do I append an option to an HTML select with javaScript?

Date: 2009jul6
Updated: 2017may16
Language: javaScript
Platform: web

Q.  How do I append an option to an HTML <select> with javaScript?

A.  This function does the trick:

function appendSelectOption(objSelect, pretty, value, is_selected) { if (objSelect == null) return false; var options = objSelect.options; options[options.length] = new Option(pretty, value, false, is_selected); return true; }
An example:
<select id=myselect> </select> <script> var obj = document.getElementById('myselect'); appendSelectOption(obj, 'Yes', 'yes', false); appendSelectOption(obj, 'No', 'no', false); appendSelectOption(obj, 'Maybe', 'maybe', true); </script>
Using this from jquery:
appendSelectOption($('#myselect')[0], pretty, value, is_selected);