tdjfdjdj
tdjfdjdj

Reputation: 2471

Dynamically generated radio buttons make checked=true in Javascript

I have dynamically generated radio buttons based on an array. The name and id of radio buttons auto increment up from 1.

The problem is I can't access their id or name inside the for loop.

var t;
for(var i=0; i<k.length; i++) //k is the array of values selected.
{
    t = "t" + i;
    // 'i' is the auto incremented radio button name and id
    if (document.form1.getElementById(t).value == k[i]) 
    {
        // need 'i' to auto increment up to match radio button name and id
        //document.form1.i.checked = true; 
        document.form1.getElementById(t) = true;
    }
}

Radio buttons built via XSL:

<xsl:for-each select="a/b">
    <input id="t{autoincnum}" type="radio" name="t{autoincnum}" value="{c[@value='1']/@value}"/>
    <input id="t{autoincnum}" type="radio" name="t{autoincnum}" value="{c[@value='2']/@value}"/>
    <input id="t{autoincnum}" type="radio" name="t{autoincnum}" value="{c[@value='3']/@value}"/>
</xsl:for-each>

Upvotes: 1

Views: 1610

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69915

Try this

for(var i=0; i<k.length; i++) //k is the array of values selected.
{
  // 'i' is the auto incremented radio button name and id
if (document.getElementById("rb_"+i).value == radiobuttonname[i]) 
{
  // need 'i' to auto increment up to match radio button name and id
    document.getElementById("rb_"+i).checked = true; 

}

}

Upvotes: 1

Philipp Kyeck
Philipp Kyeck

Reputation: 18830

try using a name which contains (and starts) with a letter:

for(var i=0; i<k.length; i++)
{
  var btnName = "btn"+i;
  var btn = document.getElementById(btnName);
  // do sth with button ...
}

Upvotes: 1

Related Questions