cannot with Number,sent the text on the screen

Asked

Viewed 53 times

0

document.querySelector('button').addEventListener('click', calcular)

function calcular() {
  peso = document.getElementById('peso').value
  peso = peso.replace(",", ".")
  peso = Number(peso)
  altura = document.querySelector('#altura').value
  altura = altura.replace(',', '.')
  altura = Number(altura)
  res = document.getElementById('res').value = (peso / (altura ** 2)).toFixed(2)
  if (peso == '' || altura == '') {
    alert('[Erro],Precisa inseri todos os campos!')
  } else if (res > 0 && res < 18.5) {
    alert(res)
    //não está mostrando o resultado na tela
    res.innerHTML = res
    res.innerHTML += res.toString()
    document.body.style.background = 'yellow'
  } else if (res < 24.9) {
    alert('oikkkk')

    document.body.style.background = 'black'
  } else if (res < 29.9) {
    alert('oi')
    //mesmo informando o res não mostra nada
    res.innerText += 'oi'
  }

}
<!DOCTYPE html>
<html lang="pt-BR">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Imc</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <h1>IMC</h1>
  </header>
  <main>
    <section>
      <div>
        <p>Vamos calcular o imc
          <button>calcular</button>
        </p>

        <input type="text" name="peso" id="peso" placeholder="  Exe: 95, 74.5, 30,2"> Digite seu peso
        <input type="text" name="altura" id="altura" placeholder="  Exe: 1.80 , 1.7 , 2,02"> Digite sua altura
      </div>
      <div id="res" align='center'>
        Seu resultado...
      </div>
    </section>
  </main>
  <script src="index.js"></script>
</body>

</html>

I put the Number because I wanted to use any number even with a comma, but I got to pass the replace(). Without Number I cannot show the error if both weight or height are not indicated, parsefloat has to pass eval() to show the error or inform .

2 answers

1

It seems to me that its variable "res" is with the value of the result of the calculation "(weight / (height ** 2)). toFixed(2)" and not with the desired gift element, because res.innerHTML does not work.

Try to store the gift element in a separate variable and then change its content.

resultado = (peso / (altura ** 2)).toFixed(2);
elemento = document.getElementById('res');
elemento.innerHTML = resultado;
  • achieve, did what you suggested to me and also changed another way of declaring methods and objects, thank you very much.

1


I tweaked the HTML layout just to make the problem view easier.

The main problem I saw was on this line:

res = document.getElementById('res').value = (peso / (altura ** 2)).toFixed(2)

Its intention seems to be to reference an HTML element and at the same time make use of one of its properties in the case value. It is not possible to do this in one instruction.

First reference the object and from the reference manipulate the properties, for example:

//Primeiro obtém a referência.
res = document.getElementById('res')
//Depois atribui uma valor a uma de suas propriedades.
res.value = parseFloat(peso / (altura ** 2))

In case to convert the string to number I used the function parseFloat() that analyzes an argument and returns floating point number.

I just used the method Number.prototype.toFixed() only in the IMC view because this method returns a string representing the number using fixed-point notation.

I also switched the nests of ifs for ternary conditional operators.

Finally to display the calculation result on the screen I used the property .textContent

document.querySelector('button').addEventListener('click', calcular)

function calcular() {
  peso = document.getElementById('peso').value
  altura = document.querySelector('#altura').value
  //res é referência para o div cujo o id='res'
  res = document.getElementById('res')
  //Trata as entradas e converte para float
  peso = parseFloat(peso.replace(",", "."))
  altura = parseFloat(altura.replace(',', '.'))
  //Verifica se dados são válidos
  if (isNaN(peso) || isNaN(altura)) {
    res.innerText = 'Precisa preecher os campos com valores numéricos!'
    return
  }
  //Calcula o IMC
  imc = peso / (altura ** 2)

  //Cria uma uma mensagem de acordo com o IMC.
  msg = imc > 0 && imc < 18.5 ? 'abaixo do peso':
                   imc < 24.9 ? 'com o peso normal':
                   imc < 29.9 ? 'com sobrepeso' :
                   imc < 34.9 ? 'com obesidade grau 1':
                   imc < 39.9 ? 'com obesidade grau 2':
                                'com obesidade grau 3'
                                
  //Exibe o IMC no HTML com uma mensagem personalizada.
  res.textContent = `Seu IMC é ${imc.toFixed(2)} e você está ${msg}.`                         
                          

}
input {
  display: block;
}

label {
  display: block;
}
<!DOCTYPE html>
<html lang="pt-BR">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Imc</title>
  <link rel="stylesheet" href="style.css">
</head>

<body>
  <header>
    <h1>IMC</h1>
  </header>
  <main>
    <section>
      <h5>Vamos calcular o seu IMC:</h5>
      <label>Digite seu peso
        <input type="text" name="peso" id="peso" placeholder="  Exe: 95, 74.5, 30,2"> 
       </label>
      <label> Digite sua altura
        <input type="text" name="altura" id="altura" placeholder="  Exe: 1.80 , 1.7 , 2,02"> 
       </label>
    </section>
    <br><button>calcular</button><br><br>
    <section>
      <span id="res" align='center'>          
      </span>
    </section>
  </main>
</body>

</html>

  • @Evertoncostasouza, yes you can do, will be cool. Just assign the class to the element according to IMC, just use the method Element.classList.add()

  • I will try to do and see if I can you realized that I understand little javascript kkk, and thank you very much .

Browser other questions tagged

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