Tontodoin Tontodoin - 2 months ago 6x
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;
var weatherUrl = "" + lat + "&lon=" + lon + "&units=metric";
} else {
alert("Geolocation is not supported. Enter your zip code!");

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

if (cityName) {
var weatherUrl = "" + cityName + "&units=metric";
} else {
alert("Pease enter a valid city name");



Any pointers? Thanks.

Edit: I have included the html code:

<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>


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.