Nested if - JavaScript

322 views Asked by At

I want the code to read the input value for Bz and give a greeting along with the answer from the equation. This is what I have this far. It's not giving a 'greeting' after the computation. Help?

  <html>
  <body>

<form id="function" onsubmit="return false" oninput="o.value = 3.21 + (9.63 * parseInt(Bz.valueAsNumber))">
    3.21+(9.63 *<input name="Bz" type="number" step="any">) =
   <output name="o" for="intial set Bz">0</output>&nbsp;nT

</form>

<div id="mys1"></div>

<script language="JavaScript">   
 function myMath() 
 {
    var Bz;
    var greeting; 
    if(Bz>-50)
    {
         if (Bz>-30)
         {
               greeting = "None"; 
         }
         else  
         {
               greeting = "Small ";
         }
         else 
         { 
               if (Bz> -80) 
               {
                     greeting = "Mild ";
               }
               else 
               {
                     greeting = "Large ";
               }
          }
     }
 document.getElementById("mys1").innerHTML= greeting;
 };  
</script>

</body>
</html>
2

There are 2 answers

2
pablito.aven On BEST ANSWER

I found your problem. Bz value is not being loaded. Seting input name attribute will not store the value into a variable. That attribute is for form submission.

What you should do is:

function myMath() 
 {
    var Bz = $("input[name='Bz']").val();
    ...
    ...
    ...
 }
6
pablito.aven On

Where are you calling your function myMath() from? I guess it is not being fired.

Also, the way you wrote your ifs statements is pretty ugly. This would be much nicer:

if(Bz>-30)
{
    greeting = "Small";
}
else if(Bz>-50)
{
    greeting = "Mid ";
}
else if(Bz>-80)
{
    greeting = "Large";
}
else
{
    greeting = "None";
}

Beware that I wrote this trying to guess what greeting message you actually want. Notice that if the first condition is satisfied, the other conditions will not even be checked at all.