Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addEventListener, "change" and option selection

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> </select> 

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 because 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?

like image 705
NovaDev Avatar asked Jul 21 '14 21:07

NovaDev


People also ask

What is change addEventListener?

The change event occurs when the element has completed changing. To attach an event handler to the change event of an element, you can either call the addEventListener() method: element.addEventListener('change', function(){ // handle change });

Is it better to use addEventListener or onclick?

addEventListener can add multiple events to a particular element. onclick can add only a single event to an element. It is basically a property, so gets overwritten.


2 Answers

You need a click listener which calls addActivityItem if less than 2 options exist:

var activities = document.getElementById("activitySelector");  activities.addEventListener("click", function() {     var options = activities.querySelectorAll("option");     var count = options.length;     if(typeof(count) === "undefined" || count < 2)     {         addActivityItem();     } });  activities.addEventListener("change", function() {     if(activities.value == "addNew")     {         addActivityItem();     } });  function addActivityItem() {     // ... Code to add item here } 

A live demo is here on JSfiddle.

like image 54
Austin Mullins Avatar answered Sep 20 '22 16:09

Austin Mullins


The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){       document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);       }  function addActivityItem(){       //option is selected       alert("yeah"); }  window.addEventListener("load", start, false); 
like image 26
Jack Daniels Avatar answered Sep 18 '22 16:09

Jack Daniels