ITWorker ITWorker - 2 months ago 9
HTML Question

Razor, HTML, jQuery: How to check/uncheck all checkboxes?

I have the following code in Razor and HTML:

@:<td>
<input class="privcheck"
type="checkbox"
name="selectedPrivileges"
value="@priv.PrivilegeID"
@(Html.Raw(priv.Assigned ? "checked=\"checked\"" : "")) />
@priv.PrivilegeName

@:</td>

<button id="checkallprivs">
Select All
</button>

<button id="uncheckallprivs">
Deselect All
</button>


And the following jquery:

$("#checkallprivs").button();
$("#uncheckallprivs").button();

$(document).on("click", "#checkallprivs", function (event) {
event.preventDefault();
$('.privcheck:checkbox').attr('checked', 'checked');

});

$(document).on("click", "#uncheckallprivs", function (event) {
event.preventDefault();
$('.privcheck:checkbox').removeAttr('checked');
});


When I click the "Select All" button, it checks all the boxes. After that, if I click "Deselect All" it unchecks all the checkboxes. The issue however is that once i click on the deselct button, the Select All button does not do anything when clicked. How can I get the expected behavior?

Thank you.

Answer

i would suggest using prop() instead of attr()

$(document).on("click", "#checkallprivs", function (event) {
    event.preventDefault();
    $('.privcheck:checkbox').prop('checked', true);

});

$(document).on("click", "#uncheckallprivs", function (event) {
    event.preventDefault();
    $('.privcheck:checkbox').prop('checked', false);
});
Comments