When I type in France
or france
, a country in the array, in the input field the block of code returns country not in our database
. I'd expect the code to return France is a country located in Europe
.
I've tried using the return
keyword on each conditional statement but without success. I've also read up w3schools.com's documentation on if
/else
statement.
However, I'm still unable to solve that problem. Interestingly, the else if
statement works. I mean when I leave the input field blank and then click the button the code does return field cannot be left blank
. I know my question will probably sound pretty basic but I'm still a beginner.
const btn = document.getElementById("button");
btn.addEventListener("click", function(){
fetch("https://restcountries.eu/rest/v2/all")
.then(function(response){
return response.json()
})
.then(function(data){
var userInput = document.getElementById("userInput");
var userInputValue = userInput.value;
var region = document.getElementById("region");
for(var i = 0; i < data.length; i++) {
if(userInputValue.toLowerCase() === data[i].name.toLowerCase()) {
region.innerHTML = `${data[i].name} is a country located in ${data[i].region}`
} else if (userInputValue === "") {
region.innerHTML = "field cannot be left blank";
} else {
region.innerHTML = "country not in our database";
}
}
})
})
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>API Beginners</title>
</head>
<body>
<label for="userInput">country's name</label>
<input id="userInput" type="text" name="" value="" placeholder="enter a country"><br>
<label for="button">clik here to submit</label>
<button id="button" type="click" name="button">click me</button>
<div id="region"></div>
</body>
<script src="index.js" type="text/javascript"></script>
</html>
Aucun commentaire:
Enregistrer un commentaire