Home > Net >  How to manipulate a API endpoint address based on user input
How to manipulate a API endpoint address based on user input

Time:03-03

I am playing around with some HTML and JavaScript with the end goal of creating a simple website that displays the current weather. I haven't used API's before and I have limited knowledge of JavaScript so this might be a very bad question. Can I change the endpoint address based on a user input?

I have written some front-end which displays a simple form.

<section id="weather">
            <div id="nav">
                <div id="locate">
                    <div id="container">
                        <form action="index.js">
                            <label for="location">Location:</label>
                            <input type="text" id="location" name="location" required>
                            <input type="submit" value="Let's Go!">
                        </form>
                    </div>
                </div>
                <div id="output">
                    <div id="container">
                        <!-- Output of API -->

                    </div>
                </div>
            </div>
 </section>

I was thinking that this could run a JavaScript file that gathers the input of the form HTML file and do something like this:

const location = document.getElementById(location)
http://api.openweathermap.org/data/2.5/weather?q=${location}&APPID=API

I tried programming something to do this but as I have limited knowledge of both javascript and API's I keep failing. Before I was a lot of time on this can someone tell me if this is even possible? By the way I have set-up an API key but I just haven't shown it.

Thanks,

mrt

CodePudding user response:

So this is just a very lengthy way to do it so that you can understand each step

Step 1: First you want to get access to the input element:

const locationInput = document.getElementById("location");

Step 2: Then you want to grab the value of that input element

const locationValue = locationInput.value;

Step 3: Then you'd want to use that value in the URL

const url = http://api.openweathermap.org/data/2.5/weather?q=${locationValue}&APPID=API


A much shorter way would be:

const url = `http://api.openweathermap.org/data/2.5/weather?q=${document.querySelector("#location").value}&APPID=API`;
  • Related