Dave's Brain

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);

Add a comment

Sign in to add a comment
Copyright © 2008-2018, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.