Conditional structure (if Else) javascript

Asked

Viewed 110 times

1

I am studying Javascript and I have the following problem:

<!DOCTYPE html>
<html lang="pr-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nacionalidade</title>
</head>
<body>
    De onde você é?
    <input type="text" name="nac" id="nac">
    <input type="button" value="Verificar" onclick="verif()">
    <div id="res">

    </div>
    <script>
        var nac = document.getElementById('nac')
        var res = document.getElementById('res')
        function verif(){
            if (nac == 'Brasil'){
               res.innerHTML = `Você é brasileiro `
            }else {
                res.innerHTML = `Você é estrangeiro `
            }
        }
    </script>
</body>
</html>

When running, the answer is always that of the Else structure, no matter what the user type, I could not identify the problem.

  • 1

    just add next to the nac , .value will stay like this nac.value

  • Has any answer worked out for you Alef?

  • It gave yes, I will continue doing tests to fix the matter, soon I return with more doubts, rsrs

1 answer

4


You need to take the amount within the function, because, the way it is doing only the first time the page loads the value is changed and then no more, actually also lacked specify the property value that takes the value of </input> thus two problems, example:

function carai() {
  var nac = document.getElementById('nac').value  
  if (nac === 'Brasil') {
    res.innerHTML = `Você é brasileiro `
  } else {
    res.innerHTML = `Você é estranjeiro `
  }
}
De onde você é?
<input type="text" name="nac" id="nac">
<input type="button" value="Verificar" onclick="carai()">
<div id="res">


Another way to solve the problem is to rescue only the reference and within the function call the property value that thus also the data is updated:

var nac = document.getElementById('nac');
function carai() {  
  if (nac.value === 'Brasil') {
    res.innerHTML = `Você é brasileiro `
  } else {
    res.innerHTML = `Você é estranjeiro `
  }
}
De onde você é?
<input type="text" name="nac" id="nac">
<input type="button" value="Verificar" onclick="carai()">
<div id="res">

Observing: in the comparison use three equal (===) in addition to testing type also test the value.

Browser other questions tagged

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