I'm working on a search feature for my ecom project. What I'm trying to do is take the data from an input in index.html, and then redirect to search.html while still being able to hold the data, but the page just reloads and nothing is showing up in the console field.
I'm using vanilla JavaScript and running into some issues.
This is my HTML
<form action="search.html">
<input
type="text"
placeholder="Search for products"
id="search-query"
/>
</form>
and this is my JavaScript
document.getElementById("search-query").addEventListener("focus", function () {
const search = document.getElementById("search-query").value;
const searchResults = search.split(" ");
console.log(searchResults);
});
I'm using the split method because I want each word separated by a comma. I plan on implementing a feature that displays images based on each word, but for now I just want the results to log to the console so I know I'm not getting an undefined, but nothing I try seems to be working.
I was able to get the code working just fine when I was only logging the value of the input, but I need a way to redirect to search.html, which is why I wrapped it in the form.
Change the eventlistener to input and not focus as the focus will work only when the input is focused and not on user input value.
Modified snippet:
const search = document.getElementById("search-query");
search.addEventListener("input", function () {
const searchValue = search.value;
const searchResults = searchValue.split(" ");
console.log(searchResults);
});
<form action="search.html">
<input
type="text"
placeholder="Search for products"
id="search-query"
/>
</form>