简体   繁体   中英

Add onclick event to options in select drop down dynamically

I have a drop down list created from an array in JavaScript. I want to do something with the selected value when I change the dropdown value.

var newArray = [3,5,4,6]

var container = document.getElementById('container')
var dropdown = creatSelectDropDown('thisDropdown', newArray)
container.appendChild(dropdown)

function creatSelectDropDown(id, array) {

    var dropdown = document.createElement("select");
    dropdown.id = id;

    for (var i = 0; i < array.length; i++) {
        var option = document.createElement("option");
        option.text = array[i];
        option.value =  array[i];
        dropdown.options.add(option);
    }


    return dropdown;
}

So in the above code I would either have :

option.onclick = dosomething();

Or

dropdown.onchange = dosomething(getvalueofoptiontag);

I'm obviously missing something simple here ...

Fiddle to play with : https://jsfiddle.net/reko91/hnLxt4xh/1/

Can bind a function to change with this syntax:

dropdown.onchange = function(event) {
   console.log(event);
}

or using eventListener:

dropdown.addEventListener("change", function(event) {
   console.log(event);
}, false);

What you are doing wrong is that you have to pass a function to the onchange event, like:

var dosomething = function() { /* do something */}
dropdown.onchange = dosomething;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM