addEventListener, "change" and option selection
Another way to make your code understandable is :
let selector = document.getElementById("Selector");
let result = document.getElementById("result");
// when client clicked on select element
selector.addEventListener("click", () => {
// if default value is changed
selector.addEventListener("change", () => {
// if value switched by client
switch (selector.value) {
case "add":
//do somthing with , "add" value
result.innerHTML = selector.value;
break; // then take break
case "remove":
//do somthing with , "remove" value
result.innerHTML = selector.value;
break; // then take break
}
});
});
#Selector{
margin: 1rem 0;
}
<label for"Selector">chose an option:</label>
<select id="Selector" name="Selector" >
<option value="add">Add new item</option>
<option value="remove">Remove existing item</option>
</select>
<div id="result">option selected : "The default value is first option"</div>
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);
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.