Search code examples
jqueryradio-buttonchecked

Check Radio Buttons by Class


$(".test").each(function(i) {
  this.checked = true;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" value="1" name="radio" class="test" id="tr1" />
<input type="radio" value="1" name="radio" class="radio" id="tr2" />


<input type="radio" value="1" name="radio" class="radio2" id="tr3" />
<input type="radio" value="1" name="radio" class="test" id="tr4" />
<button class="button">Click</button>

I have two sets of radio buttons and I would like to have the class "test" ticked by default.

How would I go about doing this with radio buttons as we can now only tick one radio button


Solution

  • You should name the two sets differently because if they are all named radio only one of them can be checked at a time. Simply rename the second set to something else like radio2 in my example below and then the sets will work independent of each other.

    $(".test").each(function(i) {
      this.checked = true;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="radio" value="1" name="radio" class="test" id="tr1" />
    <input type="radio" value="1" name="radio" class="radio" id="tr2" />
    
    
    <input type="radio" value="1" name="radio2" class="radio2" id="tr3" />
    <input type="radio" value="1" name="radio2" class="test" id="tr4" />
    <button class="button">Click</button>