0

I have a function that creates a dropdown list from an array

function populateDropdown(){
var select = document.getElementById("dropdownList");
    var array = ["1", "2", "3"];
        for(var i =0; i < array.length; i++)
        {
        var opt = array[i]
        var ele = document.createElement("option");
        ele.textContent = opt;
        ele.value = opt;
        select.appendChild(ele);
        }
    }

With the following HTML:

<select id = "dropdownList">
        <option> Choose a vendor </option>
    </select>

I have a javascript function that will change the web page's functionality based on which dropdown item is being used. The new_vendor should be the name of the dropdown item, in this case either "1", "2", or "3".

function changeVendor(new_vendor)

How would I add something like an onClick to the dynamic dropdown and call the changeVendor function with that item name?

2 Answers 2

3

Use change event on select:

document.querySelector("#dropdownList").addEventListener("change",function(e){
   //here code for change option

   changeVendor(this.value);// in this.value is current value of select
});

Standard binding will work because select is on page from beginning ( DOM load ), only options are added dynamically, but this have no meaning for select change event.

Sign up to request clarification or add additional context in comments.

Comments

2

You can attach event handler to parent element, and get information about clicked element from event object.

var select = document.getElementById("dropdownList");
select.addEventListener('click', function(event){
    var opt = event.target.innerText;
    changeVendor(opt);
})

2 Comments

Click event should not be used in select, second click on the same option will run the code, clicking os select without chosing option also will call this callback. Next thing all Your code inside callback has no sense, everything is in select without entering options, so this.value give as value.
@MaciejSikora You are right about this.value. Not sure about browser support of 'change' event though, but I like your suggestion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.