Objectif Lune joins Upland Software.Learn more >

Back to all How-tos

Dynamically adding options to an HTML drop-down

In this How-To we’ll explore how to dynamically add new options to an HTML drop-down, or in other words, how to add new <option> elements to a <select>.

This can be useful if you have a variable number of things to show as a selection to a user. For example, choosing a color or a size for a t-shirt, selecting a batch size for a print job, a format for a printed picture, etc.

Method 1: Using data from a Detail Table

This is the simplest method, as it only needs a simple loop going through the table and adding the elements as it goes. We’ll assume the data does not need to be filtered, since that should be done in whatever data source you’re using.

Let’s imagine we have a <select> element with the ID of tshirtsize, and we have the following table somewhere in our data model:
Example data model including 6 t-shirt sizes

The script to add all 6 sizes to the drop-down would be the following (with the selector being #tshirtsize ):

var sizes = record.tables.sizes;
for each (size in sizes) {
	results.append('<option value="'+size.fields.tag+'">'+ size.fields.display + ' (' + size.fields.price + ')' +'</option>');

The append() function adds the HTML string containing the new value inside of the <select>, at the end of all the existing options, so in this case the entries in the drop-down are added in the same order they are found in the detail table.

Method 2: Loading from a JSON source file

You might have realized from some other how-tos and training material, we kind of love JSON. This format makes it pretty simple to exchange just a bunch of strings in a specific structure defined by… well, you.

So let’s take the following JSON structure, similar to the data model above, in a snippet called “sizes.json”:

    {"tag":"XS", "display":"Extra Small", "price": "$14.99"},
    {"tag":"S", "display":"Small", "price": "$14.99"},
    {"tag":"M", "display":"Medium", "price": "$15.99"},
    {"tag":"L", "display":"Large", "price": "$15.99"},
    {"tag":"XL", "display":"Extra Large", "price": "$16.99"},
    {"tag":"XXL", "display":"Extra, Extra Large", "price": "$16.99"}

The code for this (obviously pretty similar to the above, also!) would be this:

var sizes = loadjson("Snippets/sizes.json");
for each (size in sizes) {
	results.append('<option value="'+size.tag+'">'+ size.display + ' (' + size.price + ')' +'</option>');

About External Resources
Obviously, this doesn’t need to be an internal JSON file. It can be something on a network drive, on a website or even served by a back-end process, say, in Workflow. However, remember that the more external resources you load, the more expensive it will be in terms of output creation time! All those small requests do take a toll.

Leave a Reply

Your email address will not be published. Required fields are marked *