Adding options to a <select>
using jQuery?
Replace 'yourSelectId'
with your <select>
ID. Also, edit 'Display Text'
and 'Option Value'
as they represent display text and option value, respectively.
Inserting a single option
Let's say you just need to tack on a single option to your <select>
:
This line of code creates and adds a new option with 'optValue'
as the value and 'One lonely option'
as the display text. Remember to replace 'mySelect'
with the actual Id of your <select>
in the HTML.
Adding multiple options from a data collection
If you're dealing with a collection of data and need to add each piece as an option (who needs 'em one by one, anyway?):
Here, we're using jQuery's $.each
to run a function on each item in our dataset. This function creates and inserts an option for every item — power of automation, folks!
Pre-selection of an option
Want to give your users a jumping start and pre-select one of the options? Well, here you go:
Use the selected
attribute, set it to true
and voilà! The option is automatically selected upon becoming a part of the <select>
family.
Pure JavaScript — No jQuery, no problem!
Sometimes all you have is vanilla JavaScript. You can still roll something good:
The DOM's options.add()
comes in handy for times like these. It inserts the new option, no jQuery needed.
On improving efficiency
Appending options individually updates the DOM with each addition. When dealing with a large number of options, consider concatenating them as a string and adding them all at once to ensure better performance.
Dodging escaping issues
To avoid handful escaping issues (aka "The Quotes Predicament"), construct your <option>
element via the object-oriented way — look, no strings:
This approach ensures characters like quotes are skilfully escaped in your options' text or values.
Was this article helpful?