Loop through radio buttons on a form using a construted variable name

forms, javascript, radio-button

Solution

Use square bracket notation.

function loopDeLoop (xyz) {
    var elems = form.elements[xyz + "_name"],
        len = elems.length,
        i;
    for (i=0;i<len;i++){
        console.log(elems[i];
    }
}

Problem

I have several radio buttons on a form all grouped in 3's, and when they are clicked I need to run a JS function on them. In this function I loop through the radio buttons in the group of the button that was pressed (i.e. if the group was called 'abc_name' id use `for (var i = 0; i < form.abc_name.length; i++){ }`). I'm wondering if there is a way to action a group of radio buttons in the same way using a constructed group name? For example if I passed 'xyz' to the function I'd need the code to be `for (var i = 0; i < form.xyz_name.length; i++){ }`. Thanks.

Original source