Dynamically generated select option dropdown menu using JavaScript

23,313

Solution 1

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...

Solution 2

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>
Share:
23,313
sefirosu
Author by

sefirosu

...not much to say for now...

Updated on October 21, 2020

Comments

  • sefirosu
    sefirosu over 3 years

    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>';
    }
    
  • Stephen Ngethe
    Stephen Ngethe about 7 years
    Thanks for this to avoid population on the menu with previous option when user changes option add below before your FOR statement var $select = $('#mySelect'); $select.find('option').remove();