What’s wrong with my code?

Asked

Viewed 139 times

-2

I wanted to create a system that asked the nationality of the user and if he answered "Brasileiro", the if would lead to a response. Should any other nationality, the else would take you to another, at least that was my goal. However, the message does not appear.

You know how you can help me?

function clica() {
    var r = window.document.getElementById('nac')
    var r1 = window.document.getElementById('div#res')
    var r2 = (r.value)
    if (r2 == 'Brasileiro') {
        r1.innerHTML = `Olá, você é ${r}, certo?`
    } else {
        r1.innerHTML = 'Hi, what language do you speak?'
    }
}
<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Sistema de Identificação de Nacionalidade</title>
    <style>
        body {
            background-color: grey;
        }
    </style>
</head>

<body>
    <h1>SISTEMA DE IDENTIFICAÇÃO</h1>
    Qual sua nacionalidade? <input type="text" id="nac">
    <input type="button" value="Clique" onclick="clica()">
    <div id='res'>RESULTADO:</div>
</body>

</html>

  • As Javascript is "Case Sensitive" you will soon have problems if someone puts "Brazilian" or "BRAZILIAN" (uppercase / minusculas and etc) then in "if R2" put "if (R2.toLowerCase() == 'Brazilian')". The toLowerCase function turns everything into minute

2 answers

4

In your code, you are using the function getElementById, this way one should use the id of the elements to access them via javascript, just change this line to use the id of the element 'res':

 var r1 = window.document.getElementById('res')

The element with id = div#res does not exist in your html.

Also modify how the message is displayed inside the comando condicional if html script.

r1.innerHTML = `Olá, você é ${r2}, certo?`

It’s not in the question but I would recommend using the strict equality (===):

 if (r2 === 'Brasileiro') {

2


If you give a F12 and watch Console tab of the browser you will see that your code is giving the following error.

Uncaught TypeError: Cannot set property 'innerHTML' of null

Try to take the figures this way

var r = window.document.getElementById('nac')
var r1 = window.document.getElementById('res')

It’s not related to the question, but I suggest you use it like this in your answer for when you are Brazilian

r1.innerHTML = "Olá, você é "+r2+", certo?"

Browser other questions tagged

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