0

I made this simple code to check all checkboxes in a gridview

function chkFun() {
        if ($("#chkSelectAll").is(':checked')) {
            $("#grdSearchResults tr").each(function () {
                debugger
                var checkBox = $(this).find("input[id*='chkSelected']");
                $(checkBox).attr("checked", true);
            });
        }
        else {
            $("#grdSearchResults tr").each(function () {
                debugger
                var checkBox = $(this).find("input[id*='chkSelected']");
                $(checkBox).attr("checked", false);
            });
        }
    }

chkFun will called in the chkAll checkbox OnClicking.. and it is working fine in the 1st time [selecting & deselecting] .. after that it is not working at all and i don't know why.

I tried to debugg it as u see in code it go right in everywhere .. but this line $(checkBox).attr("checked", false); is not doing any thing after the first time

Alok
  • 1,290
  • 1
  • 11
  • 21
Mahmoud
  • 197
  • 1
  • 5
  • 16

1 Answers1

4

Use .prop() instead of attr()

function chkFun() {
    if ($("#chkSelectAll").is(':checked')) {
        $("#grdSearchResults tr").find("input[id*='chkSelected']").prop('checked', true);
    } else {
        $("#grdSearchResults tr").find("input[id*='chkSelected']").prop('checked', false);
    }
}

Also you don't need to use .each(), you could select all with one line

Or you could bind the function to chkSelectAll and use the code Satpal recommended in the comments to make the code even shorter

$('#chkSelectAll').on('change', function () {
    $("#grdSearchResults tr").find("input[id*='chkSelected']").prop('checked', this.checked)
});
Anton
  • 32,245
  • 5
  • 44
  • 54
  • Ok, `.prop()` works fine .. can you explain the reason why `.attr()` wasn't a good function here ?? – Mahmoud Jan 29 '14 at 12:24
  • .attr doesn't work with boleean values @Mahmoud There's a good post here explaining prop vs attr http://stackoverflow.com/a/5876747/1696560 – Anton Jan 29 '14 at 12:26
  • 1
    if block can be removed and code can be improved with `$("#grdSearchResults tr").find("input[id*='chkSelected']").prop('checked', this.checked)` – Satpal Jan 29 '14 at 12:27
  • 1
    @Satpal i just noticed, this.checked won't work because `this` is not scoped into the function so this.checked wont work :/ – Anton Jan 29 '14 at 12:29