NovaDev NovaDev - 7 months ago 35
Javascript Question

addEventListener, "change" and option selection

So I'm trying to have dynamic select list populate itself, from a single selection to start:

<select id="activitySelector">
<option value="addNew">Add New Item</option>

and then JavaScript code we have:

addEventListener("select", addActivityItem, false);

The problem is that various events don't fire when you have one item: not "change" because, the text is no different when you select that item; not "select" (as I have here), for a roughly similar reason, because I'm not really selecting anything b/c there's only one item. What is the event that should be fired here? It seems silly to list a blank item in my option list to fire the event, so I hope there is another solution. Or is that the best solution?


You need a click event to handle the kind of behavior you've describe.

First, check to see if more than one option already exists.

If not, call your addActivityItem function.

The following snippet demonstrates how you may achieve that:

var activities = document.getElementById("activitySelector");

activities.addEventListener("click", function() {
    var options = activities.querySelectorAll("option");
    var count = options.length;
    if(typeof(count) === "undefined" || count < 2)

activities.addEventListener("change", function() {
    if(activities.value == "addNew")

function addActivityItem() {
    // ... Code to add item here

A live demo is here on JSfiddle.