1

I have a form where the user is presented with a list of radio buttons. There is also an option to select all buttons in a certain column. The select works fine the first time, but when I want to switch back and forth between the two, it breaks.

How can I have all radio buttons in a single column get selected using just one click?

function checkAll(e) {
  if (e.hasClass('allFirst')) {
    $('.first').attr('checked', 'checked');
  } else {
    $('.second').attr('checked', 'checked');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="radio" name="A" class="first" />1</td>
    <td>
      <input type="radio" name="A" class="second" />2</td>
  </tr>
  <tr>
    <td>
      <input type="radio" name="B" class="first" />1</td>
    <td>
      <input type="radio" name="B" class="second" />2</td>
  </tr>
  <tr>
    <td>
      <input type="radio" name="C" class="first" />1</td>
    <td>
      <input type="radio" name="C" class="second" />2</td>
  </tr>
</table>
<input type="radio" name="all" class="allFirst" onclick="checkAll($(this));" />Select All #1
<input type="radio" name="all" class="allSecond" onclick="checkAll($(this));" />Select All #2

If you "Select All #1", then "Select All #2", then "Select All #1" again, the third attempt will not check the radio buttons.

https://jsfiddle.net/jb7gfev9/

Dryden Long
  • 10,072
  • 2
  • 35
  • 47

3 Answers3

1

Try changing attr to prop.

See this question for more information.

Community
  • 1
  • 1
clarmond
  • 358
  • 1
  • 7
1

You need to use jquery .prop() instead of .attr()

function checkAll(e) {
  if (e.hasClass('allFirst'))
    $('.first').prop('checked', true);
  else
    $('.second').prop('checked', true);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input type="radio" name="A" class="first" />1</td>
    <td>
      <input type="radio" name="A" class="second" />2</td>
  </tr>
  <tr>
    <td>
      <input type="radio" name="B" class="first" />1</td>
    <td>
      <input type="radio" name="B" class="second" />2</td>
  </tr>
  <tr>
    <td>
      <input type="radio" name="C" class="first" />1</td>
    <td>
      <input type="radio" name="C" class="second" />2</td>
  </tr>
</table>
<input type="radio" name="all" class="allFirst" onclick="checkAll($(this));" />Select All #1
<input type="radio" name="all" class="allSecond" onclick="checkAll($(this));" />Select All #2
Mohammad
  • 21,175
  • 15
  • 55
  • 84
1

Just to add a bit of context to Mohammad's answer, in this case .attr() applies to the default state while .prop() applies to the current state of the DOM tree, hence its value in toggling here. In situations where your user can update attribute values, you'll want to use .prop() to get the current values.

Rich
  • 3,156
  • 3
  • 19
  • 29