Mark / uncheck all dynamically created checkboxes

3

I'm creating checkboxes from the DB. I have another one that defines whether all the others are marked or not. When I run the first time it works fine, but the second one does not.

HTML

<div class="row smart-form">
  <section class="col col-3">
   <div class="checkbox">
     <label>
      <input type="checkbox" name="selectAll" id="check0" class="checkbox style-0 checkDoc">
      <span>Marcar/Desmarcar todos</span>
     </label>
   </div>
  </section>
 </div>
<div class="row smart-form">
 @for(dt <- docTipo) {
  <section class="col col-3">
    <div class="checkbox">
     <label>
      <input type="checkbox" name="docTipo" id="[email protected]" class="checkbox style-0">
      <span>@dt.descricao</span>
     </label>
    </div>
  </section>
 }
</div>

JQUERY

$(document).on('change','.checkDoc', function() {
            if(this.checked) {
                $("input[name=docTipo]").attr("checked", true);
                $("input[name=docTipo]").attr("disabled", true);
            } else {
                $("input[name=docTipo]").attr("checked", false);
                $("input[name=docTipo]").attr("disabled", false);
            }
        });

When the first click on the control checkbox all the others are selected and disabled, the second click is all de-selected and enabled, the third one is only disabled but not marked. I already inspected the element, and the checked one is added in each one but in the browser the visa does not appear: s

Inspect Element

Any suggestions?

    
asked by anonymous 10.03.2015 / 18:09

2 answers

3

You should use .prop() and not .attr() ". The documentation for .attr() contains the following explanation:

  To retrieve and change DOM properties such as the checked , selected , or disabled state of form elements, use the .prop() method .

In Portuguese:

  

For DOM properties such as checked , selected , or disabled element elements form or checkboxes use .prop()

However these lines all within the event handler could be reduced to:

$(document).on('change', '.checkDoc', function () {
    $("input[name=docTipo]").prop({
        checked: this.checked,
        disabled: this.checked
    });
});

jsFiddle: link

    
10.03.2015 / 18:20
3

Use on click and prop instead of attr

$(document).on( "click",'input[type=checkbox][name=selectAll]', function() {
    var isChecked = $(this).is(':checked');
    $('input[type=checkbox][name=docTipo]').prop('checked',isChecked);
});
    
10.03.2015 / 18:18