Changing a global var with .click & .val | weather API

Changing a global var with .click & .val | weather API
0

#1

Hi all

I have declared a 'city’var in my code which I would like to update with the input val of a search box - to let users search for their city. Can’t seem to get this one working however. Any advice is well appreciated. I’ve left a link for the codepen below:

 var city = "Cork";
  
  $("#submit").click(function(){
    
    city = $("#area:text").val();
  });
  
  console.log(city);
  
  var api = "https://api.apixu.com/v1/current.json?key=cb6ead03cdbd4efa91a172859161211&q=" + city;

#2

You want to call the weather API after the user clicks the button. Currently it only gets called on page load.
I’d copy the assignment to api into the click callback function, and call from there the $.getJSON. Also, currently when the user clicks the submit button, the page reloads (because the form’s action is set to ‘#’), and city defaults to ‘Cork’. you can prevent the page reloading by adding

$("#submit").click(function(e) {
     e.preventDefault();
     ...
}

in your click handler


#3

Seems to work for me


#4

Thanks @vdineva , it’s starting to work now :slight_smile:


#5

Cheers @MARKJ78 ; just changed the code and it’s doing what I want now. Just got back from Manchester actually - it was bloody freezing!


#6

haha yes, certainly is.