Search code examples
javascripthtmlarraysgoogle-chrome-extensiondropdownbox

Dropdown box not showing Array in Chrome Extension


I'm using an array in order to populate a dropdown box.

I want to have the dropdown box working in a chrome extension I'm building - i.e contents of the dropdown are populated by the array.

I'm running into an issue where the chrome extension does not seem to display the array in the dropdown box, however, if I run the file as a regular HTML page (not a browser extension) the dropdown box works as intended.

*First image is of the file run as a html page

  • enter image description here

*Second image is of the same file being run as a chrome extension (no options available in the dropdown) - enter image description here

The array = 0,1,2,3,4,5

HTML

<div class="dropdown">
    <select id="dropBox" onchange="getValue()"></select>
</div><br><br> 

JS

var dropBox = document.getElementById("dropBox");
var locales = [0,1,2,3,4,5];
for (var i=0; i<locales.length; i++){
    dropBox.options.add(new Option(locales[i]));
}

function getValue(){
    var drop_val = dropBox.options[dropBox.selectedIndex].value;
    alert(drop_val);
}

Solution

  • Set up a listener for onchange on the select-element instead of calling an inline Javascript-function from your HTML-file.

    var dropBox = document.getElementById("dropBox");
    dropBox.onchange = getValue
    
    var locales = [0,1,2,3,4,5];
    for(var i in locales) {
        dropBox.add(new Option(locales[i]));
    }
    
    function getValue(e){
        var drop_val = e.target.value;
        // Do whatever you would like to do with 'drop_val'
    }
    <div class="dropdown">
        <select id="dropBox"></select>
    </div>