Search code examples
htmljqueryformsradio-button

Check latest checked radio button?


I have a huge table of radio buttons, for example, these are their IDs:

  a1 a2 a3 a4 a5 a6
  b1 b2 b3 b4 b5 b6
  c1 c2 c3 c4 c5 c6

Row a is selected by default, and each column is grouped together (by name) so that if user selects b3, a3 will become unselected. The problem is that if the user does click b3, my jquery code returns a1, because it is the first radio button :checked in my HTML.

How can I get the latest :checked radio button in chronological order?

This is my jquery code:

 $('#fontPicker input').on('change', function() {
   one = $("#fontPicker input[type='radio']:checked")[0]['id'];
   console.log(one);
 });

The only way I can figure it out is to make a function for each group, but that's repetitive and defeats the purpose of coding, right?


Solution

  • Since, to group the radios we use the name attribute, you can find the selected by group using the [name=GROUP] attribute selector.

    And you get the group of the clicked input using $(this).attr('name').

    Also, instead of input[type='radio'] you can use input:radio selector.

    See demo below.

    $('#fontPicker input').on('change', function() {
       var group = $(this).attr('name');
       var one = $("#fontPicker input:radio[name='"+group+"']:checked")[0]['id'];
       console.log(one);
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    
    <table id="fontPicker">
      <tr>
        <td><input type="radio" name="c1" id="a1"></td>
        <td><input type="radio" name="c2" id="a2"></td>
        <td><input type="radio" name="c3" id="a3"></td>
        <td><input type="radio" name="c4" id="a4"></td>
        <td><input type="radio" name="c5" id="a5"></td>
        <td><input type="radio" name="c6" id="a6"></td>
      </tr>
      <tr>
        <td><input type="radio" name="c1" id="b1"></td>
        <td><input type="radio" name="c2" id="b2"></td>
        <td><input type="radio" name="c3" id="b3"></td>
        <td><input type="radio" name="c4" id="b4"></td>
        <td><input type="radio" name="c5" id="b5"></td>
        <td><input type="radio" name="c6" id="b6"></td>
      </tr>
      <tr>
        <td><input type="radio" name="c1" id="c1"></td>
        <td><input type="radio" name="c2" id="c2"></td>
        <td><input type="radio" name="c3" id="c3"></td>
        <td><input type="radio" name="c4" id="c4"></td>
        <td><input type="radio" name="c5" id="c5"></td>
        <td><input type="radio" name="c6" id="c6"></td>
      </tr>
    </table>

    Of course, there is a variety of ways you could accomplish the same:

    var one = $("#fontPicker input:radio:checked").filter("[name='"+group+"']")[0]['id'];
    var one = $("#fontPicker input:radio:checked").filter(function() { return $(this).attr('name') === group; })[0]['id'];
    

    But choosing which one is a matter of taste.