点击后选中javascript复选框

时间:2016-04-22 05:47:42

标签: javascript jquery html checkbox

我有一个Datatable,其中我试图显示一个复选框,当点击任何一行时,它的复选框将被选中

这是我的表

<table class="bt-datatable table table-striped" id="bt-user-datatable">
    <thead>
    <tr>
      <th><input type="checkbox" name="select_all" value="1" id="bt-select-all"></th>
      <th class="text-left">name</th>
      <th class="text-left">gender</th>
      <th class="text-left">class</th>
    </tr>
    </thead>
    <tbody>
    <%
         @user.each do |user|

    %>
            <tr class="bt-users-row">
              <td class="text-left"><input type="checkbox" value="<%= user.id %>"></td>
              <td class="text-left"><%= user.name %></td>
              <td class="text-left"><%= user.gender %></td>
              <td class="text-left"><%= user.class %><div 
            </tr>
    <% end %>
    </tbody>
  </table>

在javascript中我有

    $('.bt-users-row').on('click', function(){
            var checkBox = $(this).find('input[type="checkbox"]');
            if (checkBox.is(':checked')){
                checkBox.prop("checked", false);
            }
            else if (!checkBox.is(':checked')) {
                checkBox.prop("checked", true);
            }
        });

所以在这个我想要做的是当我在行中点击它自动选择受尊重的复选框但是,我有一个问题是当我点击复选框,它没有检查

1 个答案:

答案 0 :(得分:3)

问题是,当选中复选框时,执行默认操作和行检查代码,否定操作

$('.bt-users-row').on('click', function(e) {
  if ($(e.target).is(':checkbox')) {
    return;
  }
  $(this).find('input[type="checkbox"]').prop('checked', function() {
    return !this.checked;
  });
});
相关问题