user3725310
user3725310

Reputation:

JavaScript else if not working

I have a simple screen with 2 text boxes, one to enter Methane data, One ot enter Hydrogen Data, I have written a little JS to divide one by the other. As below.

<script type="application/javascript">  
function RRC()
    {
        var Methane = document.getElementById('MethaneVPM').value;
        var Hydrogen = document.getElementById('HydrogenVPM').value;
        var RRC1 = Methane / Hydrogen;
        var RRR1 = parseFloat(RRC1).toFixed(1);

        if (!isNaN(RRR1)) 
            {
                document.getElementById('RogerRatio').value = RRR1;
            }
    }
</script>

This works with an on focus, If I put 62 in Methane and 52 in Hydrogen I get 1.2, which is correct.

However when I add some else if statements to it, it fails. I've been looking at this for days now, I know I am missing something I just can't work out what.

So below just stops responding.

<script type="application/javascript">  
function RRC()
    {
        var Methane = document.getElementById('MethaneVPM').value;
        var Hydrogen = document.getElementById('HydrogenVPM').value;
        var RRC1 = Methane / Hydrogen;
        var RRR1 = parseFloat(RRC1).toFixed(1);
        var RRC1R = 0;

        if(RRR1 < 0.1){RRC1R = 5;}
        else if(RRR1 >= 0.1 && < 0.9){RRC1R = 0;}
        else if(RRR1 >= 1 && < 2.9){RRC1R = 1;}
        else if(RRR1 >= 3){RRC1R = 2;}
        else {RRC1R = 'Boo';}

        if (!isNaN(RRC1R)) 
            {
                document.getElementById('RogerRatio').value = RRC1R;
            }
    }
</script>

Any pointers at this stage would be a huge help.

Thanks in advance

Upvotes: -1

Views: 3687

Answers (2)

marosu
marosu

Reputation: 26

You are missing RRR1 in your conditions. I would also suggest to change condition as follows:

<script type="application/javascript">  
function RRC()
   {
    var Methane = document.getElementById('MethaneVPM').value;
    var Hydrogen = document.getElementById('HydrogenVPM').value;
    var RRC1 = Methane / Hydrogen;
    var RRR1 = parseFloat(RRC1).toFixed(1);
    var RRC1R = 0;

    if(RRR1 < 0.1){RRC1R = 5;}
    else if(RRR1 >= 0.1 && RRR1 < 1){RRC1R = 0;}
    else if(RRR1 >= 1 && RRR1 < 3){RRC1R = 1;}
    else if(RRR1 >= 3){RRC1R = 2;}
    else {RRC1R = 'Boo';}

    if (!isNaN(RRC1R)) 
        {
            document.getElementById('RogerRatio').value = RRC1R;
        }
}
</script>

Upvotes: 0

hairmot
hairmot

Reputation: 2975

You're missing a value in your if statements:

 else if(RRR1 >= 0.1 && < 0.9)

should be

 else if(RRR1 >= 0.1 && RRR1 < 0.9)

the same goes for all conditions

see the working code here

Upvotes: 8

Related Questions