【问题标题】:Selecting multiple radio buttons with "Select All" option使用“全选”选项选择多个单选按钮
【发布时间】:2017-02-03 04:52:17
【问题描述】:

我有一个表单,向用户显示单选按钮列表。还有一个选项可以选择某一列中的所有按钮。选择第一次工作正常,但是当我想在两者之间来回切换时,它会中断。

如何一键选中单列中的所有单选按钮?

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

如果您“全选 #1”,然后“全选 #2”,然后再次“全选 #1”,第三次尝试将不会检查单选按钮。

https://jsfiddle.net/jb7gfev9/

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    您需要使用 jquery .prop() 而不是 .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

    【讨论】:

      【解决方案2】:

      尝试将 attr 更改为 prop

      更多信息请参见this question

      【讨论】:

        【解决方案3】:

        只是为了给 Mohammad 的回答添加一点上下文,在这种情况下 .attr() 适用于默认状态,而 .prop() 适用于 DOM 树的当前状态,因此它在此处切换的值。在您的用户可以更新属性值的情况下,您需要使用 .prop() 来获取当前值。

        【讨论】:

          猜你喜欢
          • 2016-05-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-03-12
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多