How can I effectively display the city weather information that I have chosen from the drop-down menu?

Is there a way to display city weather information that I have selected from a drop-down menu using JSON? I am able to retrieve the city using jQuery, but I am not sure how to load the weather data for that city. Any guidance on this would be appreciated.

index.php

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>
    <body>
        <div class="weather-container" style="background:#ccc;text-align:center">
            <img src="" alt="" class="icon">
                <p class="city"></p>
                <p class="weather" style="font-size: 22px;margin:0"></p>
                <p class="temp" style="font-size: 60px;margin:0;font-weight:bold"></p>
                <select name="" class="select_city" id="">
                    <option value="Lahore">Lahore</option>
                    <option value="Karachi">Karachi</option>
                    <option value="Islamabad">Islamabad</option>
                    <option value="Perth">Perth</option>
                    <option value="Berlin">Berlin</option>
                </select>
        </div>
    </body>
</html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="script.js"></script>

script.js

$(document).ready(function(){
    $("select.select_city").change(function(){
        var selectedCountry = $(this).children("option:selected").val();
        alert("You have selected the country - " + selectedCountry);
    });
});
var cityy = "Lahore";
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + selectedCountry + "&units=metric&APPID=d89208ad904d31a4402384ff1d4d1a2f", 

function(data){
    console.log(data);

    var icon = "https://openweathermap.org/img/w/" + data.weather[0].icon + ".png";
    $('.icon').attr("src", icon);

    var temp = Math.round(data.main.temp);
    $('.temp').append(temp);

    var weather = data.weather[0].main;
    $('.weather').append(weather);

    var city = data.name;
    $('.city').append(city);
});

Answer №1

For the variable "selectedCountry" to be accessible to other functions, it needs to be declared as a global variable. This issue stems from scope and context.

To address this, define the variable like this: var selectedCountry = null;

Then, within the document.ready function, assign a value to selectedCountry without using the var keyword.

Example:

selectedCountry = selected values through Javascript

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incomplete Backbone and Ajax request handling

When attempting to retrieve the value for rhOptions through an ajax call, I am encountering a problem where the view is rendering this value as "undefined". Below is a snippet of my View code: UserView.prototype.initialize = function() { var self; ...

Responsive CSS design that adjusts to fit the content

Struggling to make the wrapper expand with its content... This is the structure: * { padding: 0; margin: 0; } body { background-color: #ccc; background-repeat:repeat; font: Tahoma, Geneva, sans-serif; color: #FFF; } .wrapper { width: 95%; margin: 0 au ...

Ensure that a group of checkboxes is mandatory

I currently have a series of checkboxes set up like so: <label>What is your preferred movie genre?</label> <div class="custom-control custom-checkbox"> <input type="checkbox" class="custom-control-input" id="genre1" name="genre" ...

Having trouble with Selenium and Java when sending keys to a text field - no errors though

I am currently using Selenium with Java in Eclipse for automating test cases on a website as a way to improve my skills. Below is the HTML code snippet. https://i.sstatic.net/I2lCP.jpg My project is set up using Page Object Model in Maven, however, I am ...

What is the best way to determine the size of CSS elements relative to other elements?

Is there a way to calculate the size of an element by using calc() or any other method based on the size of another DOM element? ...

Use CSS to mimic the :hover functionality for touchscreen devices

I am struggling to get this piece of code to function correctly, $(document).ready(function() { $('.hover').bind('touchstart touchend', function(e) { e.preventDefault(); $(this).toggleClass('hover_effect'); }); ...

Is misbehavior expected at approximately 600 pixels in width?

What is happening with my website when the width is minimized, and how can I resolve it? Issue The website appears fine on mobile devices and full screens, but at reduced sizes, the background image disappears and the top bar behaves strangely (with the l ...

Is there a way to ensure all images have uniform height using CSS?

I manage a dating platform where I showcase user profiles along with their profile pictures. In case a user doesn't have a profile picture, I show a specific default image. Below is the code snippet: @register.inclusion_tag(filename='accounts/pr ...

The background color of social media links spills over onto other links, creating a messy overlap

I have been trying to confine the teal hover effect within the boundaries of my social media links. Despite adjusting padding, heights, and widths using CSS properties, the hover effect still extends beyond the right border. Here is how it appears without ...

"Error occurs when attempting to insert indexes into a JSON array, causing the Dat

I am facing an issue with my datatable setup. I have a php array that is converted to a JSON array and populates the table successfully. However, when I try to add calculated fields to the table using PHP, it seems like Datatables is unable to read them pr ...

Position the title of the Bootstrap selectpicker field to the right

I utilized Creative Tim's Material Dashboard Pro to create a select field. My goal is to align both the select field and its options to the right. Currently, I have only been successful in aligning the options while the title and selected option rema ...

The utilization of Display Flex resulting in the enlargement of the containing div

I am currently learning CSS and trying out some new things. I am looking to create a page with two side-by-side divs: one for the sidebar and the other for the main content. My goal is to have the sidebar take up 400px of width and allow the content part t ...

Encountering a JSON Parsing Issue within an Android Application

I'm facing an issue in my Android app where I am attempting to retrieve popular media from Instagram. To achieve this, I am utilizing the JSONParser class featured in a tutorial available at public class JSONParser { static InputStream is = nu ...

Sending a request via AJAX to retrieve a complicated object

Programming Environment: ASP.NET, jQuery Below is the AJAX call I am using: var tempVar = JSON.stringify({plotID:currentId}); $.ajax({ type: "POST", url: "testPage.aspx/getPlotConfig", data: tempVar, contentType: ...

React - Material UI Divider not centered

Is the title says - my divider is not centered in the middle of my text. The current result displays a misalignment: However, I am aiming for my divider to be placed in the center like this (refer to red line): It's quite strange because according t ...

The whitespace issue stems from the div element __next-build-watcher generated by next js and usecontext

There's a notification bar at the bottom of my page that lets the user know when their email has been sent. This bar is generated using useContext in React/Next.js. To see the code, check out this Codebox link: Code However, I've noticed there ...

Updating borderWidth dynamically in react native fails to produce the desired effect

Here is the code I am working with: const [focused, setFocused] = useState(false); <TextInput style={{ ...styles.inputStyles, borderColor: `${focused ? colors.darkPurple : "#b8b8b850"}`, borderWidth: `${focused ? 3 : 1}`, }} placeh ...

Guide on retrieving the button value within a foreach loop by utilizing the post method

Aim: Retrieve the values of buttons using the $_POST method within a foreach loop $projects= 'Project1, Project2, Project3'//from MySQL database $projectNames = explode(',', $projects); // separating project names to display individua ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...

What is the best way to create this using html and css?

Struggling to recreate a design I was given: I currently have this setup: How can I insert vertical lines spanning the full height between the options? <ul id="navigation"> <li><a href="#">Log In</a></li> <li> ...