Sometimes, we want to add a listener which is called if less than 2 options on a select element with JavaScript.
In this article, we’ll look at how to add a listener which is called if less than 2 options on a select element with JavaScript.
How to add a listener which is called if less than 2 options on a select element with JavaScript?
To add a listener which is called if less than 2 options on a select element with JavaScript, we listen to the click event.
For instance, we write
<select id="activitySelector">
<option value="addNew">Add New Item</option>
</select>
to add the select element.
Then we write
const activities = document.getElementById("activitySelector");
const addActivityItem = () => {
//...
};
activities.addEventListener("click", () => {
const options = activities.querySelectorAll("option");
const count = options.length;
if (typeof count === "undefined" || count < 2) {
addActivityItem();
}
});
to select the select element.
And then we call addEventListener
to add a click event listener to the drop down.
In it, we check if there’re less than 2 options with
const options = activities.querySelectorAll("option");
const count = options.length;
and count < 2
.
We get all the options in the drop down with activities.querySelectorAll("option")
.
If count
is undefined or if it’s less than 2, then we call the addActivityItem
function.
Conclusion
To add a listener which is called if less than 2 options on a select element with JavaScript, we listen to the click event.