JavaScript Check Box

0

I'm doing maintenance on a system, and I found the following code:

$(".MinhaClass").die();
$(".MinhaClass").live('click', function () {
    // Código
}

.MinhaClass refers to a list of checkbox . I was asked to add a checkbox to the list Everyone at the top of the list. I soon thought of doing:

$("#selecionar-todos").change(function () {
      $('#lista input:checkbox').each(function () {
           $(this).click();
      });
});

Soon the system would behave in the same way as before, without many changes. When you click select all, all items in the list are checked, including the "Select All" checkbox, but when you click on an item individually, it is unchecked and the "Select All" checkbox should also be unchecked. Home For this, it would be necessary to identify in the first code where the click action comes from, if it was called by the method that I created or was triggered by the mouse click individually. I have this Fiddle to explain it better.

  

Note: The problem is that the Select All checkbox should only be   marked when all items are checked, if any   unchecked, the select all checkbox should also be unchecked ...

    
asked by anonymous 26.10.2015 / 17:43

1 answer

1

Change the code to

$(function(){
  $("#selecionar-todos").change(function() {
    $("#lista input:checkbox").prop('checked', this.checked);
  });
  $("#lista input:checkbox").change(function() {
    if (!this.checked) { // se desmarcou, limpa "selecionar todos"
      $("#selecionar-todos").prop('checked', false);
    }
  });
});
label {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><label><inputid="selecionar-todos" type="checkbox"/>Selecionar Todos</label>
<div id="lista">
    <label><input name="itens" type="checkbox" value="1"/>Item1</label>
    <label><input name="itens" type="checkbox" value="2"/>Item2</label>
    <label><input name="itens" type="checkbox" value="3"/>Item3</label>
    <label><input name="itens" type="checkbox" value="4"/>Item4</label>
</div>

To assign the tag I used the checked native property instead of the click event (which toggles the selection), this property can be accessed with the .prop() " or directly if it is a native object (such as this.checked of code)

    
26.10.2015 / 17:48