I wanted to get the value in the input field after clicking the search
button and set it in the localStorage
then store it in the the searchKey
variable and pass it in the main()
to search the movies in omdbapi.
I tried using the onsubmit
in the form and passed in the browse(event)
to see if I can get the value in the input field. However, when I console.log(event.target.value)
the input value is not showing up after clicking the search
button.
const movieListEl = document.querySelector('.shows');
const searchKey = localStorage.getItem("key");
async function main (event) {
const url = `https://www.omdbapi.com/?apikey=39a36280&s=${encodeURI(event)}`;
const search = await fetch(`${url}`);
const data = await search.json();
// console.log(data.Search)
movieListEl.innerHTML = data.Search.map((movie) => movieHTML(movie)).join("");
}
main(searchKey);
function browse(event){
event.preventDefault();
console.log(event.target.value);
localStorage.setItem("key", event.target.value);
}
function movieHTML (details) {
return `<div class="shows__content">
<figure class="shows__poster">
<img src="${details.Poster}" alt="" class="poster">
</figure>
<div class="poster__description">
<h4 class="poster__title">${details.Title}</h4>
<p class="poster__year">${details.Year}</p>
</div>
</div>
`
}
<form action="" id="movie__searchbox" class="nav__search-bar"
onsubmit="browse(event)">
<input type="text" id="searchbar" class="nav__search" placeholder="Search" />
<button type="submit" >
Search</button>
</form>
<div class="shows"></div>
2
Answers
Issue
By accessing
event.target.value
in thebrowse
function, you’re getting the value of the form instead of the value of the input.Potential Solution
I edited your snipped and gave the input a name of
searchbarinput
so that thebrowse
function could reference it by name.Note: I only commented out the
localStorage.setItem
so that the example would run on Stack OverflowAlternative:
You could also pass the form (
event.target
) to the FormData constructor.Why do you get the value of the search button through
event.target
? Theevent
object corresponds to the form submission as far as I remember so it’s better to get it directly.Also, inline attributes like
onsubmit()
are a bad practice, use theaddEventListener()
method instead.And, call the
main()
function, update local storage, and get<input>
‘s value when the form is submitted.And, here’s your final code.
I commented everything related to local storage because it doesn’t work in Stack Snippets.
See this JSFiddle for a working version using local storage.