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?
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 });
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With