Convert a List into a Select Dropdown using jQuery
Look around the Internet and you’ll find lots of JavaScript in-place editor libraries that allow you to convert display text into an editable field. Just as interesting, but less common, is the select-in-place list. That works much the same way as in-place text editing, but allows the user to select from an ordered or unordered list by converting it into a dropdown lends itself very well to voting polls. Say that you had a list of fruits. You could decide to submit your own choice by clicking on it. That might be a frivolous thing to be voting on, but in a world where the color of a dress can break the Internet, why not?
Depending on whether we wanted to list the items in order of importance, we could use either an ordered or unordered list. Both have exactly the same syntax, except for the outer tags, which are
- and
- What’s your favorite fruit?
- apples
- oranges
- bananas
- strawberries
- raspberries
- melons
- grapes
- tangerines
- What’s your favorite fruit?
- apples
- oranges
- bananas
- strawberries
- raspberries
- melons
- grapes
- tangerines
- What’s your favorite fruit?
- apples
- oranges
- bananas
- strawberries
- raspberries
- melons
- grapes
- tangerines
- respectively. Here is the markup and resulting lists produced by both tags:
<UL class="dropdown">
<LH>What's your favorite fruit?</LH>
<LI>apples</LI>
<LI>oranges</LI>
<LI>bananas</LI>
<LI>strawberries</LI>
<LI>raspberries</LI>
<LI>melons</LI>
<LI>grapes</LI>
<LI>tangerines</LI>
</UL>Did you know that lists support the
Referencing jQuery
As alluded to in the title, we’re going to use jQuery to generate the by passing in the tag name. The replaceWith() function instantly swaps the list with the new element. The option text is retrieved from the list element and set on the option using the html() function. The value attribute is set using the index argument that is passed to the each() function. Feel free to substitute a more meaningful value for your application.
var $list = $(this),
$select = $('<select />');
$list.children('li').each(function(index) {
$select.append($('<option />').attr('value', index).html($(this).html()));
});
$list.replaceWith($select);