What is wrong with my simple JS exercise?

Asked

Viewed 32 times

0

I’m trying to run the practical Javascript course exercise for beginners, but it’s not working out. And I don’t know why, the Inspector doesn’t point out mistakes either.

The exercise is about Conditions (if, else). In my attempt ALWAYS appears the result Else, even having written "Brazil" in the input.

What I did wrong?

Follows the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PRÁTICA  </title>
</head>
<body>
    País: <input type="text" name="país" id="país">
    <input type="button" value="Check" onclick="verificar()">
    <div id="resultado"></div>

    <script>
        function verificar() {
            var país = window.document.getElementById('país')
            var res = window.document.getElementById('resultado')
            if(país == 'Brasil') {
                res.innerHTML = 'Você é brasileiro!'
            }else {
                res.innerHTML = 'Você é estrangeiro!'
            }
        }
    </script>
</body>
</html>

1 answer

2


Hello,

The variable país is an HTML element, you have to use the attribute value of the object país.

Try this:

if (país.value === 'Brasil') {
  • Thank you! In the case with numbers you don’t need, is that it? If you can ask me one more question... What do I do if I wanted to accept both Brazil and Brazil (with tiny initial)? I tried so "if(country.value == 'Brazil' && 'brazil')", but it did not work

  • Not at all! If you can mark the answer as resolved, I thank you :)

  • 2

    Yes. Still need to use the .value, and in the second case, you have to check as follows: if (país.value == 'Brasil' || país.value == 'brasil'). Turns out, if you use the operator &&, the condition would have to be Brazil and Brazil at the same time... And you have to use .value == for each test :)

  • Oops, I get it! Thank you very much for the answers! I’ll mark it as solved :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.