Javascript variable reset after leaving if statement?-Collection of common programming errors

I’m brand new to javascript with a C# background, so I was intrigued when I stumbled onto the following situation:

EDIT: I’ve included the original text reproducing the issue. The alert text is showing as “undefined”. Am I correctly querying the radios?

index.html


    
        
    

    
        
            10 
20
30

scripts.js

function buttonPressed()
{

var radios = document.getElementsByName("group1");
var checkedRadio;

for(var i in radios)
{
    if(radios[i].checked)
    {
        checkedRadio = i;
    }
}

var tipAmount;

if(checkedRadio == 0)
{
    tipAmount = 10;
}
if else(checkedRadio == 1)
{
    tipAmount = 20;
}
if else(checkedRadio == 2)
{
    tipAmount = 30;
}

alert(tipAmount);
}

Why is alertText undefined?

Thanks

  1. JavaScript has no block scope, only function scope. So the code you gave us will work.

  2. This code should work, I suggest you to download Firebug so you will have access to the script and put a break point at the first line and press F10 to debug on every lines and you should find the error quickly or tell us what it does.

    Can you try with a loop like this

    for( i = 0; i < radios.length; i++ ) 
    {
        if(radios[i].checked)
        {
           checkedRadio = i;
        }
    
    }
    

    Also you could use the value in your checkbox instead of hard coding the tip.

    Do you have jquery?

    You could do something easy like this

    $('.group1:checked').each(function() {
    tip = this.val();
    });
    

Originally posted 2013-11-09 20:18:44.