sefirosu
sefirosu

Reputation: 2648

Dynamically generated select option dropdown menu using JavaScript

This is the select menu I am going to create. But as you can see there are static data. As I actually have bunch of JSON data passed from backend servlet, so there will be hundreds of items for options. I want something like dynamically generate option menu for my dropdown box.

<select id="brand-select" name="brand">
    <option value="audi">Audi</option>
    <option value="bmw">BMW</option>
    <option value="lexus">Lexus</option>
</select>

This is my tryout and it doesn't work:

HTML:

<select id="brand-select" name="brand" onChange="createOptions">
    <option value="none"></option>
</select>

JavaScript:

//Asssume I have jsonDataForBrands ready, and it contains 100s items
function createOptions() {
    for (var fieldIndex in jsonDataForBrands) {
        html += '<option value=' + fieldIndex  + '>' + jsonDataForBrands[field].title + '</option>';
}

Upvotes: 3

Views: 25901

Answers (3)

sefirosu
sefirosu

Reputation: 2648

I figured it out by myself...

HTML:

<select id="brand-select" name="brand">
                </select>

JavaScript:

function creatBrandOptions(){
    for (var field in jsonDataForBrands) {
         $('<option value="'+ jsonDataForBrands[field].name +'">' + jsonDataForBrands[field].title + '</option>').appendTo('#brand-select');
    }
}

I did an Ajax call to retrieve JSON data from my servlet and then creatBrandOptions() in the same function BTW...

Upvotes: 4

Eamonn Gormley
Eamonn Gormley

Reputation: 2446

You beat me to it. Here's a complete simplified example of adding options to a select using jquery:

<html>
<head>
<script src="jquery.js"></script>

</head>
<body>
<button id="populateMenu" >Populate menu</button>

<select id="mySelect">


</select>

<script>
    var optionValues= [[1,"first"],[2,"second"]];

    jQuery("#populateMenu").click( function () {
        for (var i=0;i<optionValues.length;i++){
            jQuery('#mySelect').append(jQuery("<option></option>").val(optionValues[i][0]).text(optionValues[i][1]))
        }
    });
</script>
</body>
</html>

Upvotes: 1

bitfhacker
bitfhacker

Reputation: 292

This example uses jQuery. See if it suits you:

function createOptions( jsonDataForBrands ) {
   $('#brand-select option').remove(); // first remove all options
   for (var i=0; i<jsonDataForBrands.length; i++)

   for (var fieldIndex in jsonDataForBrands) { // then populatem them
      $('#brand-select').append($("<option></option>").attr("value", fieldIndex  ).text(jsonDataForBrands[field].title) );
}

Upvotes: 0

Related Questions