I have to start the search when search button is clicked. So I have added click event on search button. When I click on button startSearch function is called. And that function adds an event on input element. Now let's say I have typed TEXT in form and I clicked the search button, nothing happens. But If I later type something else search is activated. How to do this properly?
document.querySelector('.searchBtn').addEventListener('click',
startSearch); //button
const inputSearch = document.querySelector('.inputSearch');
function startSearch(){
inputSearch.addEventListener('keyup', searchFunction);
}
You will have to set the event listeners as soon as the HTML document is loaded (See DOMContentLoaded event). You are registering the event handler once the search button is clicked, but you need to start the search when it is clicked so you need to set the event handler before that. Then activate the search function in the event handler. An event can only be registered if an event handler is set before the event occurs.
The following implementation will start a search once the value in the input field changes or the search button is clicked.
function searchFunction(searchTerm) {
console.log(`Searching for ${searchTerm}...`)
}
window.addEventListener("DOMContentLoaded", (e) => {
const btn = document.querySelector(".searchBtn");
const input = document.querySelector(".inputSearch");
btn.addEventListener("click", (e) => {
// get value of input field first
searchFunction(input.value);
});
input.addEventListener("keyup", (e) => searchFunction(e.target.value));
});
<input class="inputSearch" />
<button class="searchBtn">Search</button>