Skip to content
Advertisement

Adding event on “Enter Key” for two filters

I just set up a couple of functions that are executed upon users pressing the “ENTER” keyword. I was wondering if anyone has a more elegant solution or if this would be the only option?

I was looking at others’ solutions and I couldn’t find anything else. The reason is that both inputs belong to the same functions thus I’m curious to see a different approach. Here is my code:

This is the code on “search btn” click:

const searchBtnHandler = () => {
    let countryValue = countryFilterAccess.value.trim().toUpperCase();
    let searchCategory = searchCategoryMenu.value.trim();
    if (countryValue === '' && searchCategory === '') {
        return;
    }
    console.log(countryValue, searchCategory);
    const results = filteredItems(countryValue, searchCategory);

    if (results.length === 0) {
        alert(`Not Items Found :(, Please Try Again`);
    } else {
        for (let el of itemElements) {
            el.style.display = 'none';
        }
        results.forEach((result) => {
            document.getElementById(result.id).style.display = 'grid';
        });
        if (!document.getElementById('cancel-search-btn')) {
            addCancelFilterBtn();
        } else {
            return;
        }
    }
};

Below the code I created for action on “ENTER”

countryFilterAccess.addEventListener('keyup', (event) => {
    if (event.keyCode === 13) {
        event.preventDefault();
        searchBtnAccess.click();
    }
});

searchCategoryMenu.addEventListener('keyup', (event) => {
    if (event.keyCode === 13) {
        event.preventDefault();
        searchBtnAccess.click();
    }
});

I just want to see if there is a way to merge the two event listeners in one function.

Thank you!

Advertisement

Answer

function callbackFn(event){
if (event.keyCode === 13) {
        event.preventDefault();
        searchBtnAccess.click();
    }
}

countryFilterAccess.addEventListener('keyup', callbackFn);
searchCategoryMenu.addEventListener('keyup', callbackFn);
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement