document.getElementById(' ').value returns undefined

Viewed 174

I am using an API for a weather app. But when it comes to create a search bar using a <input type="text"> and a document.getElementById(' ').value it returns me undefined (when I log it out). So I'm wondering if there is any other way to get the input.

HTML:

<form class="search">

     <input type="text" id="Search" name="Search" placeholder="Search city..." style="width: 50%; padding: 10px;">

     <button type="submit" id="button" style="padding: 10px;">SEARCH</button>

</form>

JavaScript:

let location1 = document.getElementById('Search').value;
let api1 = 'http://api.openweathermap.org/data/2.5/weather?q=';
let api2 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=metric';

let API = api1 + location1 + api2;

// MAIN WEATHER */
fetch(API) // Current weather API

Any help will be apreciated

1 Answers

The problem was that I set a button which function was reload the page. The solution my proffesor told me is to set the entire JS code to a function. And when the button is pressed activate that function. I leave here the working code:

HTML

<form class="search">

            <input type="text" id="Search" name="Search" placeholder="Search city..." style="width: 50%; padding: 10px;">   
            <button type="button" id="button" style="padding: 10px;" onclick="find_weather()" >SEARCH</button>
         
</form>

JS

let find_weather= function(){
        let location1 = document.getElementById('Search').value;
        let api1 = 'http://api.openweathermap.org/data/2.5/weather?q=';
        let api2 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=metric';
    
        let api3 = 'http://api.openweathermap.org/data/2.5/forecast?q=';
        let api4 = '&appid=ece23eaa3a8d940b327a0cdc41c1e344&units=Metric';
        
        let API = api1 + location1 + api2;
        let API2 = api3 + location1 + api4;

        
        fetch(API).then(response => response.json())
        ...

thanks everyone who helped me ily <3

Related