Tontodoin Tontodoin - 3 months ago 12
Javascript Question

How do I restructure the document.ready function to allow for the button click?

I have a jQuery function which would get the current position and use an API to request the current weather condition. I have it inside the document.ready() function so that the page loads to display the current location. I also have a .click() function for a button which takes in a city name and does another api request. However, after the API call the page reloads again resulting in the first API call again. I don't understand how to restructure the function such that their execution is isolated. Here's my code:

$(document).ready(function() {
$.ajaxSetup({ cache: false });

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(data) {
var lat = data.coords.latitude;
var lon = data.coords.longitude;
console.log(lat);
console.log(lon);
var weatherUrl = "http://api.openweathermap.org/data/2.5/weather?lat=" + lat + "&lon=" + lon + "&units=metric";
extractVals(weatherUrl);
});
} else {
alert("Geolocation is not supported. Enter your zip code!");
}

$("#formSubmit").click(function() {
btnClicked = true;
var cityName = $("#cityText").val();
console.log(cityName);

if (cityName) {
var weatherUrl = "http://api.openweathermap.org/data/2.5/weather?q=" + cityName + "&units=metric";
} else {
alert("Pease enter a valid city name");
}

extractVals(weatherUrl);
});

});


Any pointers? Thanks.

Edit: I have included the html code:

<form>
<input type="text" class="form-control" id="cityText" name="city" placeholder="Enter your city"><br>
<button type="button" id="formSubmit" onclick="submitBtn(event);">Submit</button>
</form>

Answer

You haven't shown your HTML, but I'm going to guess that #formSubmit is a type="submit" button (note that that's the default type of button elements).

Clicking a submit button submits the form, making it load the result of the form in the page. If you don't want the button to do that, make it a type="button" button or use preventDefault (or return false) in your handler.

Comments