I'm trying to use a simple API that displays information about countries. In the var apiCall
I can hardcode a country at the end of the url and the getJSON
method works as intended and displays the information.
var apiCall = "https://restcountries.eu/rest/v1/name/england";
$.getJSON(apiCall, function(data){
$("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);
$("#capital").html("Capital: " + data[0].capital);
$("#region").html("Region: " + data[0].region + " - " + data[0].subregion);
...
I want to add the country name afterwards, with user input:
HTML:
<input type="text" placeholder="Country Name" id="inputText"></input>
<button id ="searchButton"> Search </button>
JS
var inputText = $("#inputText");
var apiCall = "https://restcountries.eu/rest/v1/name/";
$("#searchButton").click(function(){
return apiCall = apiCall + inputText.val();
});
If instead of return I do a console.log
, I get a string like the one that works at the beginning, if the user type "england", then I get "https://restcountries.eu/rest/v1/name/england"
$.getJSON(apiCall, function(data){
$("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);
$("#capital").html("Capital: " + data[0].capital);
$("#region").html("Region: " + data[0].region + " - " + data[0].subregion);
...
What can I do so the $("#searchButton").click(function(){}
actually changes the value of the apiCall
and makes the getJSON
run again with that new value?
This should work
$("#searchButton").click(function(){
apiCall = apiCall + inputText.val();
$.getJSON(apiCall, function(data){ ... });
});