Home > Software engineering >  Select tag not firing the event handler
Select tag not firing the event handler

Time:02-05

For a project, I am using vanilla HTML/CSS/JS. I am trying to hide all items in a page, have a default option to be selected in the select tag, only show the element that has the selected id and use the dropdown menu to select periods of time and only show that particular element.

In my files, I have structured the function in this way. I have a console log to make sure to see if the code gets ran or not. It puts the log out only once and does not trigger no matter what I choose in the filter. I think the problem is with my event handler not firing but I am sure I followed the examples. What could be the problem here?

var day = document.getElementById("day");
var week = document.getElementById("week");
var month = document.getElementById("month");

period = document.getElementById("filter");
function loadPost(period) {
    // Hide all posts
    day.style.display = "none";
    week.style.display = "none";
    month.style.display = "none";
    switch (period) {
        case day:
            showDay();
            break;
        case week:
            showWeek();
            break;
        case month:
            showMonth();
            break;
    } 
    console.log(period);
}
function showDay() {
    day.style.display = "block";
}
function showWeek() {
    week.style.display = "block";
}
function showMonth() {
    month.style.display = "block";
}
period.addEventListener("change", loadPost(period.value));
        <div >
            <h1>Most Popular</h1>
            <label for="most-popular-filter">Filter:</label>
            <select name="most-popular-filter" id="filter">
                <option value="day">Day</option>
                <option value="week">Week</option>
                <option value="month">Month</option>
            </select>
            <div  id="day">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 1</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div  id="week">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 2</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>
            <div  id="month">
                <img src="images/placeholder.png" alt="most-popular">
                <h2>Most Popular 3</h2>
                <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Quisquam, quae.</p>
            </div>      
        </div>

CodePudding user response:

Use callback function and inside invoke other function:

period.addEventListener("change", ()=>loadPost(period.value));

  • Related