use a javascript array to fill up a drop down select box

前端 未结 2 1763
攒了一身酷
攒了一身酷 2020-11-29 02:15

I have a text file which I am reading and storing the data in a javascript array, it\'s a list of cuisines. I want to use the array to fill up a drop down select box. I know

相关标签:
2条回答
  • 2020-11-29 02:48

    Use a for loop to iterate through your array. For each string, create a new option element, assign the string as its innerHTML and value, and then append it to the select element.

    var cuisines = ["Chinese","Indian"];     
    var sel = document.getElementById('CuisineList');
    for(var i = 0; i < cuisines.length; i++) {
        var opt = document.createElement('option');
        opt.innerHTML = cuisines[i];
        opt.value = cuisines[i];
        sel.appendChild(opt);
    }
    

    DEMO

    UPDATE: Using createDocumentFragment and forEach

    If you have a very large list of elements that you want to append to a document, it can be non-performant to append each new element individually. The DocumentFragment acts as a light weight document object that can be used to collect elements. Once all your elements are ready, you can execute a single appendChild operation so that the DOM only updates once, instead of n times.

    var cuisines = ["Chinese","Indian"];     
    
    var sel = document.getElementById('CuisineList');
    var fragment = document.createDocumentFragment();
    
    cuisines.forEach(function(cuisine, index) {
        var opt = document.createElement('option');
        opt.innerHTML = cuisine;
        opt.value = cuisine;
        fragment.appendChild(opt);
    });
    
    sel.appendChild(fragment);
    

    DEMO

    0 讨论(0)
  • 2020-11-29 02:49

    This is a part from a REST-Service I´ve written recently.

    var select = $("#productSelect")
    for (var prop in data) {
        var option = document.createElement('option');
        option.innerHTML = data[prop].ProduktName
        option.value = data[prop].ProduktName;
        select.append(option)
    }
    

    The reason why im posting this is because appendChild() wasn´t working in my case so I decided to put up another possibility that works aswell.

    0 讨论(0)
提交回复
热议问题