0

In my html page I want to dynamically insert checkboxes, and I want to have 1 master checkbox on top, so if that is checked, then all the dynamically created ones become checked, and if it is unchecked, then all dynamically ones become unchecked. I have this code:

<script type="text/javascript">
    $(function() {
        $("#selectAll").click(function() {
            var checked = $(this).prop('checked');
            $(".profilebox").attr("checked", checked);
        });
    });
</script> 

master check box

<input id="selectAll" type="checkbox" name="selectall" value="All">

other checkboxes: (gets inserted in a loop using this php code)

<input type='checkbox' class='profilebox' name='select' value='{$member_id}'>

However it is not functioning properly. If I click the master one, then they all get checked. If I click it again, then all get unchecked, then if I click it again, they all still remain unchecked.

Does anyone know the problem?

Thanks

omega
  • 40,311
  • 81
  • 251
  • 474

3 Answers3

6

Use prop instead of attr, setting property of the element is guaranteed to work than setting attribute of the element. Older verison of jquery which did not have prop, attr used to perform the work of both, later prop was introduced and for setting properties like these prop serves the best.

$(function() {
        $("#selectAll").click(function() {
            $(".profilebox").prop("checked", this.checked);
        });
    });
Community
  • 1
  • 1
PSL
  • 123,204
  • 21
  • 253
  • 243
1

need to use .prop() to set the checked property instead of .attr()

$(".profilebox").prop("checked", this.checked);

Ex:

$(function () {
    //cache the selector result
    var $profileboxes = $(".profilebox");
    $("#selectAll").click(function () {
        $profileboxes.attr("checked", this.checked);
    });
});

Read: Attributes vs. Properties

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

Use .prop()

$(".profilebox").prop("checked", this.checked);

now your code becomes

$(function () {
    $("#selectAll").click(function () {
        $(".profilebox").prop("checked", this.checked);
    });
});

$( elem ).prop( "checked" ) true (Boolean) Will change with checkbox state

$( elem ).attr( "checked" ) (1.6) "checked" (String) Initial state of the checkbox; does not change $( elem ).attr( "checked" )

(1.6.1+) "checked" (String) Will change with checkbox state

$( elem ).attr( "checked" ) (pre-1.6) true (Boolean) Changed with checkbox state

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107