search

Home  >  Q&A  >  body text

IMC Calculator with Switch

I was working in a IMC calculator to exercise js. This calculator should shows the IMC and a message acording the result but, for some reason, it always shows the default message.

    

const form = document.querySelector('#form');
    
    
    form.addEventListener('submit',(e)=>{
        e.preventDefault();

    const weight = document.querySelector('#weight').value;
    const height = document.querySelector('#height').value;

    const bmi = (weight / (height **2)).toFixed(2);


    const value = document.querySelector('#value');
    let description = '';

    document.querySelector('#infos').classList.remove('hiden');

    
    switch(bmi){
        case bmi < 18.5:
            description = 'Cuidado! Você está abaixo do peso!';
            break;
        case bmi >= 18.5 && bmi <= 25:
            description = "Você está no peso ideal!";
            value.classList.remove('attention');
            value.classList.add('normal');
            break;
        case bmi > 25 && bmi <= 30:
            description = "Cuidado! Você está com sobrepeso!";
            break;
        case bmi > 30 && bmi <= 35:
            description = "Cuidado! Você está com obesidade moderada!";
            break;
        case bmi > 35 && bmi <= 40:
            description = "Cuidado! Você está com obesidade severa!";
            break;
        case bmi > 40:
            description = "Cuidado! Você está com obesidade morbida!";
            break;
        default:
            description = "verifique novamente";
            break;
        }
    value.textContent = bmi.replace('.', ',')
    document.querySelector('#description').textContent =description ;
   
});

I tried rewriting, using brackets in cases like this > case (bmi > 25 && bmi <= 30) 并检查了作业说明。 Algo seak 在 yt 中寻找一些使用 switch 的教程,但没有找到。

P粉231112437P粉231112437393 days ago639

reply all(1)I'll reply

  • P粉727531237

    P粉7275312372024-01-11 15:00:35

    You are opening a number, but all cases evaluate to booleans so they can match. You can instead use a series of if, else if, and else.

    Alternatively, turn on true instead, which will result in selecting the first case that evaluates to true.

    switch (true) {
        // ...
    }
    

    reply
    0
  • Cancelreply