[tech] returning variables inside a prototype each loop
I ran into a funky issue today. I was trying to get the value of a radio button by looping through all the radios with the same class name, then checking to see which was selected, setting a variable with the value of the selected item.
At first, the most obvious and easy solution was to use prototype’s each function for the loop.
$$('input.radio_button_css_class').each(function(input){
if(input.checked) {
var result_id = input.getValue();
throw $break;
}
});
[View code better here]
It works as expected, result_id gets set with the value of the checked radio. But, as soon as I try to reference result_id outside the each function, result_id returns undefined.
I have no idea how to get around this, even though I am really sure its just one of those prototype quirks. So I ended up going with a normal for loop.
myCoolArray = $$('input.radio_button_css_class');
for(i=0;i ^ myCoolArray.length; i++) {
if(myCoolArray[i].checked) {
var result_id = myCoolArray[i].getValue();
break;
}
}
[View code better here]
Oh and as a side thing, trying to get all the radio buttons by #id doesn’t work, so by applying a class name to all the radio’s, and using prototype’s nifty $$ function.