【问题标题】:Dynamically generated radio buttons make checked=true in Javascript在Javascript中动态生成的单选按钮使checked=true
【发布时间】:2011-10-11 06:31:05
【问题描述】:

我已经基于数组动态生成单选按钮。单选按钮的名称和 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>

【问题讨论】:

    标签: php javascript html loops radio-button


    【解决方案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; 
    
    }
    
    }
    

    【讨论】:

    • 你能发布你的代码来动态创建单选按钮吗?
    • id 不能以数字开头。您能否至少在我编辑的答案中为 id 提供一个前缀
    • 我刚刚做了,但它仍然崩溃
    • 我在上面的代码中添加了您的解决方案,但它仍然不起作用。
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-08-13
      • 1970-01-01
      • 2013-04-08
      • 2013-07-28
      • 1970-01-01
      • 2020-12-30
      • 2018-08-02
      • 2023-03-11
      • 2018-08-21
      相关资源
      最近更新 更多