This code populates a <select> menu with different <option> tags. This code is useful when you wish to change the contents of a HTML dropdown menu programatically.

View the demo

The HTML:

<!-- This is the "target" dropdown menu that we'll be populating.
The end user will interact with it. -->
<select id="my_dropdown" name="my_dropdown"></select>

<!-- These are some links to click that will run the code.
Your implementation will vary. For demonstration purposes only -->
<a href="#" id="swap_first_select">Swap the first set of options</a>
<a href="#" id="swap_second_select">Swap the second set of options</a>

<!-- This is our first "source" dropdown menu, from which data will
be populated. It is hidden using CSS. The end user will never interact
with it, or even know it exists. -->
<select id="first_select" name="first_select">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
</select>

<!-- This is our second "source" dropdown menu, from which data will
be populated. It is hidden using CSS. The end user will never interact
with it, or even know it exists. -->
<select id="second_select" name="second_select">
    <option value="a">Option A</option>
    <option value="b">Option B</option>
    <option value="c">Option C</option>
    <option value="d">Option D</option>
</select>

The CSS:

/* Hide the "source" select menus*/
#first_select, #second_select {
    display:none;
}

/* For demonstration purposes only: prevent elements from displaying
inline, and give them some spacing. You do not need to copy this code.*/
#my_dropdown, #swap_first_select, #swap_second_select{
    display:block;
    margin:0 0 10px 0;
}

The JS:

// When the first link is clicked...
$("#swap_first_select").click(function () {
    // Fill up the #my_dropdown select menu with data
	// from the #first_select menu
    $("#my_dropdown").empty().append($("#first_select option").clone());
});

// When the second link is clicked...
$("#swap_second_select").click(function () {
    // Fill up the #my_dropdown select menu with data
	// from the #second_select menu
    $("#my_dropdown").empty().append($("#second_select option").clone());
});