RunzWitScissors RunzWitScissors - 1 month ago 14
jQuery Question

Set MVC checkbox to readonly (or disabled) on client-side

We have several MVC checkboxes, such as:

@Html.CheckBoxFor(model => model.hasData, …)


We have conditional client-side code that needs to set all controls in a div to readonly (which includes these checkboxes):

if (someCondition) {
$('#' + divIdToDisable + ' input').attr('readonly', 'true');
}


We’ve learned that readonly doesn’t work properly on checkboxes (see below).

I’ve tried the following, but this causes no data to be posted back during a ‘save’ (see below also):

$('#' + divIdToDisable + ' input').attr('disabled', 'true');


This seems to be a common issue, however in all my research I haven’t found a good client-side solution.



Here’s my research:

Readonly on checkboxes doesn’t always work in all browsers:

Can HTML checkboxes be set to readonly?

How can I make a checkbox readonly? not disabled?

Using ‘disabled’ with MVC results in no value being posted back:

Html.CheckBox returns false if disabled, even if seleced

http://davecallan.com/posting-disabled-checkboxes-mvc-razor-views/

It’s possible to implement conditional ‘disable’ in razor code:

Asp .net mvc 3 CheckBoxFor method outputs hidden field, that hidden field value is false when checkbox is disabled with selected true

MVC 3: Conditionally Adding the Disabled Attribute with the HtmlHelpers

However these are not client side solutions.

Answer

If you want the data from your disabled checkboxes to be sent to the server, just set their state to enabled prior to your post. So, in jQuery, you could do something like this:

$("form").on("submit", function(e)
{
    $("input:checkbox").prop("disabled", false);
});
Comments