Ways in which the user can modify the city name within this inquiry

I am just beginning to learn JavaScript and I am struggling to figure out how to allow the user to change the city name in this request. Currently, it works when I manually input the city name in the code (e.g., askWeather.open("GET", "url.../london")), but how can I enable the user to input their desired city?

Any help would be greatly appreciated.

askWeather.onreadystatechange = function () {
    if (this.readyState === XMLHttpRequest.DONE && this.status == 200) {
        var response = JSON.parse(this.responseText);
        let resp = document.getElementById('result');
        let ask = document.getElementById('btn');
        ask.addEventListener('click', function () {
            resp.innerHTML = response.current_condition.condition;
        });
    }
};
askWeather.open("GET", "https://www.prevision-meteo.ch/services/json/lille");
askWeather.send();

Answer №1

For tracking the value that is typed and sending a request, you will need two event listeners.

Here's one method to allow the user to change the city:

let city = 'london'; // Default value set if user doesn't input anything
document.getElementById('city').addEventListener('keyup', (e) => {
    city = e.target.value;  
});

document.getElementById('send').addEventListener('click', () => {
    askWeather.open("GET", `url.../${city}`)
    askWeather.send();
});
<input id="city" type="text">
<button id="send">Send Request</button>

An alternative approach would be using a simple form with just one event listener:

let city = 'london';
document.getElementById('my-form').addEventListener('submit', () => {
  city = document.getElementById('city').value;
  askWeather.open("GET", `url.../${city}`)
  askWeather.send();
});
<form id="my-form" action="">
  <input id="city" type="text">
  <input type="submit" id="send">
</form>

Answer №2

Set up a variable to store the name of a city. This value can be assigned from various sources, such as user input.

const selectedCity = 'paris';
fetchWeatherData.open("GET", `https://www.weather-forecast.com/api/json/${selectedCity}`);

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

How can mongoose be used to modify user information in a database?

Hey there, I'm currently working on a personal project and came across an issue. I've successfully set up my (steam) user data to save in mongodb through mongoose. Right now, I have it set to only save a new user if they are not already in the da ...

AngularJS flexible route parameter

My AngularJS application has routes that can be either: www.website.com/blog/xyz www.website.com/blog/xyz/title/other-params In the second URL, the title parameter is used for readability purposes only and is not mandatory in the URL. Therefore, I have i ...

What is the best way to keep track of choices made in 'mat-list-option' while using 'cdk-virtual-scroll-viewport'?

I have been working on implementing mat-list-option within cdk-virtual-scroll-viewport in an Angular 14 project. I came across a demo project in Angular 11 that helped me set up this implementation. In the Angular 11 demo, scrolling functions perfectly an ...

WordPress header causing issues with Document.write()

I have a JavaScript function that utilizes AJAX to retrieve data from a PHP file. Previously, I utilized document.write(data) to display the retrieved content and it worked smoothly on its own. However, upon incorporating the script into WordPress via hea ...

AngularJS SmartyUI position not dynamically updating on SmartyStreets plugin

In my angularJS application, I am utilizing SmartyStreets' LiveAddress for address validation and autofilling two fields in a form. After the user submits the form, a message (either success or failure) is displayed in a div above the form. However, t ...

When using vue.js(2), the function window.scrollY consistently returns a value of 0

Here are some issues I'm experiencing with vuejs and router: The window.addEventListener('scroll', ...) is not being detected in my component. When I enter 'window.scrollY' in console.log, it always returns 0 to me. Scroll(Y) is w ...

Tips for dynamically updating an HTML value with Javascript

Summary of My Issue: This involves PHP, JS, Smarty, and HTML <form name="todaydeal" method="post"> <span id="fix_addonval"></span> <input type="radio" name="offer" id="offer_{$smarty.section.mem.index+1}" value="{$display_offe ...

Utilize AJAX and jQuery to seamlessly submit a form

I am attempting to use jQuery and AJAX to submit a form in order to add a row to a table called cadreSante (which is in French). The code I am using for this operation is provided below. Can someone please identify any errors in the code and suggest ways t ...

Creating types for React.ComponentType<P> in Material-UI using TypeScript

I am currently working with Typescript and incorporating Material-UI into my project. I am trying to define the component type for a variable as shown below: import MoreVert from '@material-ui/icons/MoreVert' import { SvgIconProps } from '@ ...

Ways to safeguard your API endpoint

Just starting out with Node.js/Express, I'm looking to have my front end retrieve data from an endpoint ('/1') without displaying the JSON data to users when they access that specific endpoint. Any guidance on how to accomplish this would be ...

Issue with setTimeout function when used in conjunction with an ajax call

Currently, I am developing a quiz portal where questions are organized in modules. Each module consists of 5 questions: the first 4 are text-based, and the 5th is an image-based question. Upon registering through register.php, users are directed to index. ...

HTML5 Mouse Canvas

Here's a simple example of what's happening: function handleClick(event) { ... } canvas.addEventListener("click", handleClick, false); function drawRectangle(x, y) { context.fillRect(x, y, 16, 16); }; ...

Struggling to capture an error generated by Sequelize within a universal Middleware block

In a test project, I have successfully implemented CLS transaction control in Sequelize using 'cls-hooked'. The transactions work seamlessly both in the command line and with Express. They are injected and managed automatically, rolling back on a ...

What is the proper way to provide login information for a webservice through a jquery ajax request?

I've been attempting to make an AJAX call using jQuery like this: $.ajax({ url: WEBSERVICE_URL, type: "GET", dataType: "application/json; charset=utf-8", username: "admin", // Most SAP ...

Connect a series of numerical input fields in Vue.js

One of the tasks I'm working on involves managing a table filled with rows of information. Users can choose multiple rows by checking checkboxes in each row, and I need to keep track of how many rows are selected by updating the totalSelected value. ...

Observing the completion of a subscriber function

Is there a more streamlined way to determine if the subscriber has finished executing or return something and catch it up-stream? Consider the following code snippets: this._subscriptions.push(this._client .getCommandStream(this._command) // R ...

Upon refreshing the page, an inline script was not executed due to its violation of the Content Security Policy directive: "script-src 'self'"

When I refresh the page on my production build for all routes except "/", I encounter an error in my Node/React app which results in a blank page being displayed. The error message states: "Refused to execute inline script because it violates the followi ...

What is the best way to utilize eslint in Vue components?

I'm facing an issue with my .vue file that defines a component. Other .vue files are unable to see it properly due to linter errors. I keep getting ES Lint errors like: Cannot find module '../components/LinkButton'. I have tried several st ...

Troubleshooting jQuery masonry problem related to initial display and height settings

Within a div, there is a masonry container with the inline style property display:none. With several divs on the page, clicking their respective buttons during load causes them to switch like a slideshow. This disrupts masonry's ability to calculate t ...

I aim to decrease the number of decimal places in the code provided below

When working on an HTML page, I encountered a challenge with the decimal numbers displaying more positions than desired - for instance: 13.16 instead of 13.167. Despite my attempts to rectify this using the code snippet below, it is still not functioning ...