动态生成的单选按钮在Javascript中使checked = true

时间:2011-07-22 18:02:09

标签: php javascript html loops radio-button

我已根据数组动态生成单选按钮。单选按钮的名称和ID自动从1开始递增。

问题是我无法在for循环中访问他们的id或名称。

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;
    }
}

通过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>

2 个答案:

答案 0 :(得分:1)

尝试使用包含(并以字母开头)的名称:

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

答案 1 :(得分:1)

试试这个

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; 

}

}