Answer the question
In order to leave comments, you need to log in
How to display the temperature in the browser from the city entered in the input?
Guys, need help. It is necessary to display the temperature in the city specified in the input by submitting the form. If there is no such city or it is entered incorrectly, display the inscription - “there is no such city”. I get data from openweather. What needs to be corrected in the code so that any city can be entered, and not just the one specified in the city variable?↓
Form
<form>
<input class="inp" type="text" placeholder="Введите город" value="">
<button class="btn">Узнать температуру</button>
</form>
<div class="result">
<h2>Результат: <span class="total"></span></h2>
</div>
const form = document.forms[0];
const insert = document.querySelector('.total');
let btn = document.querySelector('.btn');
let cityName = document.querySelector('.inp');
form.onsubmit = function(e) {
e.preventDefault();
let DATA = JSON.parse(xhr.responseText);
if(cityName.value == city) {
insert.innerHTML = DATA.main.temp - 273;
} else {
insert.innerHTML = 'такого города нет';
}
}
const APIKey = '**********************';
let city = 'Moscow';
const url = 'http://api.openweathermap.org/data/2.5/weather?q='+ city
+'&appid='+APIKey;
let xhr = new XMLHttpRequest();
xhr.open('GET', url, false);
xhr.send();
Answer the question
In order to leave comments, you need to log in
You yourself appropriated And herelet city = 'Moscow';
if(cityName.value == city) {
insert.innerHTML = DATA.main.temp - 273;
} else {
insert.innerHTML = 'такого города нет';
}
You wonder why Barnaul is not Moscow. const form = document.forms[0];
const insert = document.querySelector('.total');
let btn = document.querySelector('.btn');
let cityName = document.querySelector('.inp');
form.onsubmit = function(e) {
e.preventDefault();
const url = 'http://api.openweathermap.org/data/2.5/weather?q='+ cityName.value+'&appid='+APIKey;
fetch(url).then(response=>{
let DATA = response.json();
if('main' in DATA && 'temp' in DATA.main){
insert.innerHTML = DATA.main.temp - 273;
} else {
insert.innerHTML = 'такого города нет';
}
}
}
const APIKey = '**********************';
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question