R
R
Romchikyoyo2019-01-27 21:28:41
JavaScript
Romchikyoyo, 2019-01-27 21:28:41

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>

Script
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

1 answer(s)
S
Somewhere Intech, 2019-01-27
@john36allTa

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.
In general, look at the error from api for a request with a non-existent city and check for this error, not city (I can’t say more precisely - there is no apiKey)
But even after that it won’t work for you - you built the wrong request logic.
Alternatively, you can do this:
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 question

Ask a Question

731 491 924 answers to any question