Reputation: 121
I want to build a website where if I enter a city name I can see the temperature. This is my code but for some reason it is not working! Please help!
First I will show the JavaScript code and then I will show te HTML code.
$(document).ready(function(){
$('#submitWeather').click(function(){
var city = $("#city").val();
if (city != ''){
$.ajax({
url: 'https://api.openweathermap.org/data/2.5/weather?q=' + city + "&units=metric" + "&APPID=xxx",
type: "GET",
dataType: "jsonp",
success: function(data){
var widget = show(data);
$("#show").html(widget);
$("#city").val('');
}
});
}else{
$("#error").html('Field cannot be empty');
}
});
});
function show(data) {
return "<h3><strong>Weather</strong>: "+ data.main[0].temp +"</h3>"
}
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
<div class="row">
<h3 class="text-center text-primary">Enter City Name</h3>
<span id="error"></span>
</div>
<div class="row form-group form-inline" id="rowDiv">
<input type="text" name="city" class="form-control" placeholder="City Name">
<button id="submitWeather" class="btn btn-primary">Search City</button>
</div>
<div id="show"></div>
Does anyone know what I did wrong? Please let me know! I used this video to create the website: https://www.youtube.com/watch?v=6imiFFeDIzE
Upvotes: 0
Views: 2575
Reputation: 498
In addition to dropping the [0]
you also need to assign id='city'
to the input. You are using jquery $("#city").val()
which was coming up undefined. I ran tests in codepen and got it working. check it out on codepen
Upvotes: 1
Reputation: 96
In your show function, it tries to get data.main[0].temp
. The Open Weather Map API doesn't specify the main field as an array, it's just an object. So remove the [0]
part because it's not an array and just an object.
You also put your key in the code, so you might want to reset it.
Also, you try to select the input box with the name of city
but you actually are selecting the input box with the ID of city
, which doesn't exist. On the input element add an attribute named id
with the value being city
.
Upvotes: 1