1
var formobj = document.h1;
for (var j = 0; j < formobj.elements.length; j++) {
    if (formobj.elements[j].type == "radiobutton" && formobj.elements[j].checked) {
        var wholebase = formobj.elements[j].value;
    }
}

Later in the script, the variable is set to the inner html of a div and is labeled as undefined. Is there a flaw in my for loop?

Wilson
  • 8,570
  • 20
  • 66
  • 101

2 Answers2

0

There is no type radiobutton, I think you want type == 'radio'.

RobG
  • 142,382
  • 31
  • 172
  • 209
-1

Your wholesale variable is defined within the inner scope. Once you leave this scope the variable no longer exists. Read about Javascript scope here or here. You can change your code like this:

var wholebase = null; //<-- declare the variable here
var formobj = document.h1;   
for (var j = 0; j < formobj.elements.length; j++){
        if (formobj.elements[j].type == "radiobutton" && formobj.elements[j].checked){
        wholebase = formobj.elements[j].value;
    }
}
Community
  • 1
  • 1
Ilia Frenkel
  • 1,969
  • 13
  • 19
  • @Ilia Frenkel Actually, this is wrong. Javascript the Good Parts: "Unfortunately, JavaScript does not have block scope even though its block syntax suggests that it does. This confusion can be a source of errors." Try a simple test case where you declare some variable in a for loop then use it in the line after the loop closes. It will be visible. – AlexMA Apr 11 '12 at 02:05
  • @AlexMA You are absolutely right! That's what happens when you code in 4 different languages before lunch break :-) – Ilia Frenkel Apr 11 '12 at 02:31