alwaysLearning
alwaysLearning

Reputation: 131

Why are my if, else if and else statement not working as they should be?

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>

Upvotes: 1

Views: 2933

Answers (4)

Taha Halabi
Taha Halabi

Reputation: 171

I edit your code, don't place all the if else condition inside the for loop, checkuserinput === "" place it before beginning of the function which is the for loop. Just see my code and if you have any question just comment.

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 check = true;
   
   var userInput = document.getElementById("userInput");
   
   var userInputValue = userInput.value;
   
   var region = document.getElementById("region");
   
   if (userInputValue === "") { // First Check The User Input
        region.innerHTML = "field cannot be left blank";
   } else {
      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}`;
        check = true;
        break; // Break to not continue since we get what we need
        } else {
          check = false;
        }
      }
        
        if (check == false) {
           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>

Upvotes: 2

Robin Bastiaan
Robin Bastiaan

Reputation: 702

Your for-loop is overwriting the result on each iteration. In order to see the result, you need to break the for-loop. Something like this:

for (let 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}`
        break;
    } else if (userInputValue === "") {
        region.innerHTML = "field cannot be left blank";
        break;
    }
    region.innerHTML = "country not in our database";
}

But please note the the country not in our database section is executed on every loop, and therefore this answer does not have the best performance.

Upvotes: 2

β.εηοιτ.βε
β.εηοιτ.βε

Reputation: 39129

You’ll have to break from the for loop in the if and else if statements, otherwise the last data in the array will dictate what your element contains.

This code would give you the expected output:

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}`
        break;
      } else if (userInputValue === "") {
        region.innerHTML = "field cannot be left blank";
        break;
      } 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>


And although I would favour Neil W's answer that is much more elegant, if you want to avoid repeating useless condition you could go:

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 userInputValue = document.getElementById("userInput").value;
    var region = document.getElementById("region");
    if (userInputValue === "") {
      region.innerHTML = "field cannot be left blank";
      return;
    }
    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}`
        return;
      }
    }
    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>

This actually use return, as you wrote you tried it.

Upvotes: 4

Neil W
Neil W

Reputation: 9162

As mentioned, your loop is not breaking on finding a result. Also, worth considering doing away with the loop altogether and use the array function "find":

var existing = data.find(d => d.name.toLowerCase() === userInputValue.toLowerCase());
region.innerHTML = existing 
    ? `${existing.name} is a country located in ${existing.region}`
    : userInputValue === ""
        ? "field cannot be left blank"
        : "country not in our database";

Upvotes: 5

Related Questions