unimat
@unimat
Украина. г. Киев

Не могу вывести значение input в ссылку, полученное в переменную?

Есть страница с выводом информации о погоде. Есть массив с названиями городов, вводим название города в input, проверяем его наличие в массиве, если есть, то получаем его в переменную, которую вставляем в api ключ
<a href="https://codepen.io/orgeniuss/pen/GRZoboY"></a>
let cities = ["Киев","Харьков","Львов", "Донецк","Запорожье","Кривой рог","Николаев","Мариуполь","Луганск","Севастополь","Винница","Симферополь","Херсон","Полтава", "Чернигов","Черкасы","Хмельницкий"]

    function click () {
    let input = document.querySelector(".inputClass").value; 
    let cityId;
    document.querySelector(".button-primary").style.marginTop = 0;
    for(let i = 0; i < cities.length; i++) {
        if(cities.includes(input)) {
            cityId = input;
            break;
            }  
        }
        
    fetch(`http://api.openweathermap.org/data/2.5/weather?q=${cityId}&appid=88d4aef74677c233e595e292f6d361d6`)
    .then(function(resp) {return resp.json()})
    .then(function(data) {
        console.log(data)
        document.querySelector(".city-name").textContent = data.name;
        document.querySelector(".city-temp").innerHTML = Math.round(data.main.temp - 273) + "&deg";
        document.querySelector(".disclaimer").textContent = data.weather[0]['description'];
        let imgWrap;
         imgWrap = `<img src="https://openweathermap.org/img/wn/${data.weather[0]['icon']}@2x.png">`; 
         
         document.querySelector('.imgWrapp').innerHTML = imgWrap;
    })

.catch(function() {

})

}

document.querySelector(".submitClass").onclick = click;
  • Вопрос задан
  • 129 просмотров
Решения вопроса 1
@INRI11
под нами лишь небеса ©
<html>
<head>
</head>
<body>
	<button class="submitClass" >Нажми меня</button>
	<input type="text" value="Донецк" class = "block">

	<div class="city-name"></div>
	<div class="city-temp"></div>
	<div class="disclaimer"></div>

	<div class="imgWrapp"></div>
	<script>
		let cities = ["Киев","Харьков","Львов", "Донецк","Запорожье","Кривой рог","Николаев","Мариуполь","Луганск","Севастополь","Винница","Симферополь","Херсон","Полтава", "Чернигов","Черкасы","Хмельницкий"]

		function click () {
			let input = document.querySelector(".block").value; 
			let cityId;
			for(let i = 0; i < cities.length; i++) {
			if(cities.includes(input)) {
				cityId = input;
				break;
				}  
			}

			fetch(`http://api.openweathermap.org/data/2.5/weather?q=${cityId}&appid=88d4aef74677c233e595e292f6d361d6`)
				.then(function(resp) {return resp.json()})
				.then(function(data) {
					console.log(data)
					document.querySelector(".city-name").textContent = data.name;
					document.querySelector(".city-temp").innerHTML = Math.round(data.main.temp - 273) + "&deg";
					document.querySelector(".disclaimer").textContent = data.weather[0]['description'];
					let imgWrap;
					imgWrap = `<img src="https://openweathermap.org/img/wn/${data.weather[0]['icon']}@2x.png">`; 
					document.querySelector('.imgWrapp').innerHTML = imgWrap;
				})

			.catch(function() {

			})

			console.log(cityId);
		}
		document.querySelector(".submitClass").onclick = click;
	</script>
</body>
</html>
Ответ написан
Пригласить эксперта
Ответы на вопрос 1
KickeRocK
@KickeRocK
FrontFinish
А поточнее можно, какие ошибки?
Непонятно, что вы этим хотите сделать
for(let i = 0; i < cities.length; i++) {
        if(cities.includes(input)) {
            cityId = input;
            break;
            }  
        }

Вместо него, вот это попробуйте
if(cities.includes(input)) {
            cityId = input;            
            } else {
            return false;
            }
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы