Home > Software engineering >  Cant get value of the search bar and assign it into API
Cant get value of the search bar and assign it into API

Time:07-09

I cant assign the value to API, I tried giving it a default value then change it but it still not working (I'm new with API's), the variable is city.

searchBtn.addEventListener("click", function(){
        let searchValue = document.getElementById("searchbar").value;
          let city = searchValue;
    })
    
     fetch(`http://api.weatherapi.com/v1/forecast.json?key=${apik}&q=${city}&days=7`)

CodePudding user response:

JavaScript has scopes, and the city variable you made is declared inside of a function, while the API call is outside of the function.

You could move the API call into the function, and then it should work.

searchBtn.addEventListener("click", function(){
    let searchValue = document.getElementById("searchbar").value;
    let city = searchValue;
    
    fetch(`http://api.weatherapi.com/v1/forecast.json?key=${apik}&q=${city}&days=7`)
});

  • Related