How do I repeat select elements in HTML

Tags: javascript,jquery,html,css

Problem :

I have a select/drop down in my HTML page which has to appear about 10 times in the page. Simple sample for that would be as below:

Qn 1: {dropdown} is a {TextField}

Qn 2: {dropdown} is a {TextField}

Qn 3: {dropdown} is a {TextField}

Where dropdown lists various options which are same and static (array of strings - no server component).

I want to create the dropdown once and use it. Can CSS have data elements for the html:select? Or how do I write javascript code to fill the select elements?

Solution :

Here's one way (using jQuery to make selecting and iterating through all dropdowns easier):

<p>Qn 1: <select class="repeat"></select> is a {TextField}</p>
<p>Qn 2: <select class="repeat"></select> is a {TextField}</p>
<p>Qn 3: <select class="repeat"></select> is a {TextField}​​​​​​​​​​​​​​​​​​</p>​​​​​​​​​

<script type="text/javascript">
    var optionOpen = "<option>";
    var optionClosed = "</option>"​​​​​​​​​​​​​​​​​;​​
    var selectItems = ["firstItem", "secondItem", "thirdItem"];

        for (key in selectItems)
            $(this).append(optionOpen + selectItems[key] + optionClosed);


I formatted the select options as a list and concatenated the strings to make it easy to change and reuse between pages. Simply add options to the selectItems list to add them to each <select> tag with the class repeat. Give each <select> a different name attribute if you need the form to process them separately.

    CSS Howto..

    CSS: How to achieve - Two elements to be centered and positioned side by side WITHOUT a third parent container?

    How to prevent image moving when resizing window

    How to make TD behaving like TR(row) with CSS?

    How do I get my menu to drop down? CSS & HTML

    HTML+CSS: How to add arrow to horizontal menu items?

    How to pull all CSS rules on an element together

    How to change color of caret when drop down button is hovered

    How can I fix this 3-column layout?

    using css modules how do I define more than one style name

    How to fix content leaks out of an element despite use of “overflow:hidden”?

    How to create a completely flexible piano keyboard with HTML and CSS

    How to vertically align both image and text side by side in a div

    How To Add % Based Image To CSS? (for fluid layout)

    How to create Curved & Overlapping Menu Tabs in CSS

    How to center a div tag in a html page without being affected by zooming

    How to get divs 100% of browser using css?

    How do I absolute position a div from left to the right using media queries?

    How to get a div positioned at the bottom of a table

    How to align an icon to the right of content

    How to define alternative font-family corresponding to font-size CSS

    How to add a border-bottom similar to Yahoo! when you scroll the page?

    How to keep DIV from overlapping?

    How to equal height of