user4965201 user4965201 - 7 months ago 17
HTML Question

javascript checkbox checked when clicked away

I have a Datatable in which i am trying to show a check box and when clicked on any row its checkbox will be checked

this is my table

<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>


and in the javascript i have

$('.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);
}
});


so in this what i am trying to do is when i click in the row it automatically select the respected checkbox but , i am having an issue is when i click on the checkbox , it does not check it

Answer

The problem is, when checkbox is checked both the default action and the row check code is executed which negates the action

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