选择多个单选按钮

时间:2012-03-21 20:15:46

标签: javascript radio getelementbyid getelementsbyclassname

好吧我在php中有一个for循环,它为一个人生成一组单选按钮,组中的每个单选按钮都有相同的名称。

for ($i = 0; $i < $count; $i++) {
            echo '<tr>';
            echo '<td>' . $something[$i] . '</td>';
            echo '<td align="center"><input class="one" type="radio" name="' . $i . '" value="1"/></td>';
            echo '<td align="center"><input class="half" type="radio" name="' . $i . '" value="0.5"/></td>';
            echo '<td align="center"><input class="zero" type="radio" name="' . $i . '" value="0" checked="checked"/></td>';
            echo '<td align="center"><input class="inactive" type="radio" name="' . $i . '" value="null"/></td>';
            echo '</tr>';
        }

我希望能够通过单击链接/按钮来选择/检查具有相同类别的所有单选按钮。变量$count每隔几天就会改变一次,所以我不知道会有多少个不同的无线电组。我正在寻找这个希望在javascript

3 个答案:

答案 0 :(得分:3)

你不能这样做。单选按钮组允许单个选择。您需要使用复选框来完成此操作。

答案 1 :(得分:1)

如果类名对于单选按钮是唯一的,则可以这样做:

var radios = document.getElementsByTagName("INPUT");
for (var index = 0; index < radios.length; index++) {
   if (radios(index).type == "radio" && 
       radios(index).className.indexOf("one") > -1) {
      radios(index).checked = true;
   }
}

所有这些可能并不比为每个使用getElementsById更好,但可能比getElementsByClassName更好,这不是普遍支持的,我不认为。

答案 2 :(得分:0)

好吧,我想到了我的想法,

            $(document).ready(function() {

            // select all radio buttons in the "one" column (.one class)
            $('#select_all_one').click(function(){
                $("input[class=one]").each(function(){
                    this.checked = true;
                });
            });

            // select all radio buttons in the "half" column (.half class)
            $('#select_all_half').click(function(){
                $("input[class=half]").each(function(){
                    this.checked = true;
                });
            });

            // select all radio buttons in the "zero" column (.zero class)
            $('#select_all_zero').click(function(){
                $("input[class=zero]").each(function(){
                    this.checked = true;
                });
            });

            // select all radio buttons in the "inactive" column (.inactive class)
            $('#select_all_inactive').click(function(){
                $("input[class=inactive]").each(function(){
                    this.checked = true;
                });
            });


          });

然后选择所有收音机我使用此链接<a id="select_all_one" name="select_all" value="all_one">并将id和值的名称更改为一半,零和非活动的受尊重链接,一切正常

相关问题