Search code examples
javascriptradio-buttongetelementbyidgetelementsbyclassname

Selecting multiple radio buttons


Alright i have a for loop in php and it generates a group of radio buttons for a person, each radio button within the group has the same name.

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

I want to be able to select/check all the radio buttons with the same class by clicking a link/button. the variable $count will change every few days, so i wont know the how many different radio groups there will be. I am looking for this hopefully to be in javascript


Solution

  • okay i got mine figured out here,

                $(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;
                    });
                });
    
    
              });
    

    and then to select all the radio i use this link <a id="select_all_one" name="select_all" value="all_one"> and change the name of the id and value to half, zero, and inactive for the respected links, everything works perfect