Search code examples
javascriptcheckboxwebgrid

How to check and uncheck all checkboxes in WebGrid column?


Is there any reason why this is not working to check and uncheck the checkboxes? If I don't touch any of the checkboxes, it checks and unchecks them all on the button click event. If I manually check a box, that box will not be modified from then on, however the rest of them will continue to be modified.

How do I solve the problem?

function checkAll() {
  $('#grid tbody tr').each(function () {
    if ($(this).find("td input[type=checkBox]").is(":checked")) {
      $(this).find("td input[type=checkBox]").removeAttr("checked");
      //$(this).find("td input[type=checkBox]").attr("checked", false); //also tried this
    }
    else {
      $(this).find("td input[type=checkBox]").attr("checked", true);
    }
  });
}

Update 1:

I've made the extra loop to go through each of the checkboxes, but still get the same result. Here is the updated code:

function checkAll() {
    var count = $('#grid tbody tr').length;
    $('#grid tbody tr').each(function () {
        $(this).find("td input[type=checkBox]").each(function () {
            if ($(this).is(":checked")) {
                $(this).attr("checked", false);
            }
            else {
                $(this).attr("checked", true);
            }
        })
    });
}

enter image description here


Solution

  • According to https://api.jquery.com/attr/ you shouldn't use attr method to check and uncheck the chebox as it points to defaultChecked property and should be used only to set the initial value of the checkbox.

    Possibly it is the reason of your problem, try to use prop() instead of attr() (https://learn.jquery.com/using-jquery-core/faq/how-do-i-check-uncheck-a-checkbox-input-or-radio-button/)