Question

I am trying to use jQuery in a checkbox field to calculate the number of fields that have been checked, but I don't seem to have got the syntax correct.

Below is my attempt to count the number of fields that have been checked (there are over 20 checkbox fields).

$('#product-effect-table input[type=checkbox]').click(function()
  if($('#product-effect-table input[type=checkbox]').length == $('#product-effect-table input[type=checkbox]:checked').length) {
            $("#selectall").attr("checked", "checked");
        }
  else {
            $("#selectall").removeAttr("checked");
        }

    });

I think that the fault lies in my DOM selection.

The checkboxes are stored in a table with an id of product-effect-table

Below is a sample of the table and an input bar;

 <table id="product-effect-table">
   <td>  <input type="checkbox" name="effect5" id="effect5" value="1" checked="checked"       product_effect_id="5" /></td>
</table>
Était-ce utile?

La solution

Working Demo

mismatched {} you forgot to add brace({) .click(function () {

$('#product-effect-table input[type=checkbox]').click(function () {
    if ($('#product-effect-table input[type=checkbox]').length == $('#product-effect-table input[type=checkbox]:checked').length) {
        $("#selectall").attr("checked", "checked");
    } else {
        $("#selectall").removeAttr("checked");
    }
});

Suggested By roasted

.prop() is preferred over .attr()

so you can make use of .prop() instead of .attr()

like this :- .prop('checked',true) and .prop('checked',false)

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top