1017

I thought they could be, but as I'm not putting my money where my mouth was (so to speak) setting the readonly attribute doesn't actually seem to do anything.

I'd rather not use Disabled, since I want the checked check boxes to be submitted with the rest of the form, I just don't want the client to be able to change them under certain circumstances.

13
  • 53
    A (malicious) client can always change a checkbox's value (or send arbitrary requests). Always make sure you do proper server-side validation!
    – knittl
    Commented Aug 20, 2013 at 7:40
  • 6
    @knittl But a normal vistor has no (malicious) client. And a normal Vistor did not want to change a information (That is the sence of readonly) Commented May 27, 2014 at 9:00
  • 5
    @knittl You seem to dismiss the entire sense of readonly! Why then this attribute would exist! Commented Aug 5, 2014 at 3:13
  • 15
    @IzharAazmi: readonly is only a client-side attribute to help a browser properly render a site and then construct the correct request from it. The server cannot and should not know about the readonly attribute of the rendered page. It must assume the request came from anywhere (and possibly with malicious intentions); never rely on user-provided input. Still, why send a checkbox's value which you cannot edit in a request (if you set the value before rendering, you already know the value when the request is submitted, so there's no need to transmit it in the request)
    – knittl
    Commented Aug 5, 2014 at 6:16
  • 6
    @knittl I agree! But you see readonly attribute exists there for some reason. It has certainly nothing to do with server side implementation. But it is there to tell the user "Hey! This value is being assumed here, and/but you cannot change this." Commented Aug 5, 2014 at 9:40

49 Answers 49

731

you can use this:

<input type="checkbox" onclick="return false;"/>

This works because returning false from the click event stops the chain of execution continuing.

13
  • 40
    Returning false in javascript prevents continuing the chain of execution for the click or key handler. Has nothing to do with the checkbox's state Commented Aug 20, 2011 at 2:03
  • 11
    PS...if you want the checkbox to be in the checked state you need to add checked="checked", not mess with the javascript. The javascript is just there to force mouse clicks to be ignored on the input object, not to set state of the checkbox. Commented Aug 20, 2011 at 2:15
  • 13
    No visual indication of r/o status in this case. Commented Mar 13, 2013 at 18:58
  • 13
    Prevents from using TAB to navigate to the next input though.
    – user327961
    Commented Apr 29, 2013 at 20:57
  • 10
    Fails completely if javascript is disabled!
    – Doin
    Commented Jun 23, 2015 at 10:29
468

READONLY doesn't work on checkboxes as it prevents you from editing a field's value, but with a checkbox you're actually editing the field's state (on || off)

From faqs.org:

It's important to understand that READONLY merely prevents the user from changing the value of the field, not from interacting with the field. In checkboxes, for example, you can check them on or off (thus setting the CHECKED state) but you don't change the value of the field.

If you don't want to use disabled but still want to submit the value, how about submitting the value as a hidden field and just printing its contents to the user when they don't meet the edit criteria? e.g.

// user allowed change
if($user_allowed_edit)
{
    echo '<input type="checkbox" name="my_check"> Check value';
}
else
{
    // Not allowed change - submit value..
    echo '<input type="hidden" name="my_check" value="1" />';
    // .. and show user the value being submitted
    echo '<input type="checkbox" disabled readonly> Check value';
}
6
  • 163
    Works, but it's kind of.. well dirty, readonly on checkboxes should simply do what intuition tells.
    – levhita
    Commented Dec 16, 2008 at 21:41
  • 9
    Intuition fools us, as ConroyP explained.
    – ANeves
    Commented May 5, 2010 at 18:52
  • 147
    Intuition does not fool US, it fooled those who implemented checkbox this way.
    – Califf
    Commented Sep 21, 2013 at 15:51
  • 2
    @ConroyP -->" it prevents you from editing a field's value, but with a checkbox you're actually editing the field's state (on || off)". That's a really weak justification for a boneheaded decision. The 'state' and 'value' are, to most of us, much the same as 'toMAYto' and 'toMAHto' , as you can see by the upvotes done by the people who disagree.
    – McAuley
    Commented Oct 5, 2019 at 5:21
  • Read-only checkbox would always post my_check as checked here, even when it's not. Because hidden field is always posted and server always receives my_check=1. Commented Apr 28, 2023 at 14:09
411

This is a checkbox you can't change:

<input type="checkbox" disabled="disabled" checked="checked">

Just add disabled="disabled" as an attribute.


Edit to address the comments:

If you want the data to be posted back, than a simple solutions is to apply the same name to a hidden input:

<input name="myvalue" type="checkbox" disabled="disabled" checked="checked"/>
<input name="myvalue" type="hidden" value="true"/>

This way, when the checkbox is set to 'disabled', it only serves the purpose of a visual representation of the data, instead of actually being 'linked' to the data. In the post back, the value of the hidden input is being sent when the checkbox is disabled.

20
  • 373
    Note that "disabled" checkbox doesn't send value via POST data.
    – biphobe
    Commented Sep 20, 2011 at 13:56
  • 72
    @powtac You fail to address that he wants the data posted, your example does not do that. Commented Feb 8, 2012 at 16:59
  • 76
    There is no way this answer should have 105 upvotes. It goes against everything the OP states.
    – JM4
    Commented Dec 12, 2012 at 17:18
  • 16
    @nathanhayfield: by that logic, I should be able to post helpful answers about any topic and get upvotes. :( Commented Jul 22, 2013 at 23:39
  • 25
    @MichaelBray I'm guessing this gets a lot of upvotes because a lot of people want to know how to make checkboxes readonly so they do this: 1) Google "Checkbox readonly". 2) See that the title of this question matches what they want to do and click it. 3) Scroll down until they find this answer. 4) Happiness and upvote.
    – Mark Byers
    Commented Aug 22, 2013 at 10:22
75
<input type="checkbox" onclick="this.checked=!this.checked;">

But you absolutely MUST validate the data on the server to ensure it hasn't been changed.

5
  • 4
    I found this to be the best solution; plus, I can call another piece of code (say, some jquery-stuff) to display a nice little sign that says "you can't change this until you first do x". So something like: "...onclick='this.checked = !this.checked; javascript:theCheckboxWasClicked();'..."
    – Bane
    Commented Mar 23, 2011 at 18:47
  • This doesnt grey out the boxes as with the answer from powtac so it got my vote
    – EHarpham
    Commented Jun 29, 2013 at 17:10
  • This is a little hackish, but it is an ingenious, perfect, almost elegant little hack.
    – russell
    Commented Dec 2, 2013 at 0:50
  • 3
    As stated above, this doesn't work on double clicking in IE. I used: onchange="this.checked=true;"
    – Ritikesh
    Commented May 1, 2015 at 13:32
  • Why do you have this.checked=!this.checked? Can't you have just false? Also, I'm pretty sure the semicolon is unnecessary Commented Nov 5, 2016 at 21:39
59

another "simple solution":

<!-- field that holds the data -->
<input type="hidden" name="my_name" value="1" /> 
<!-- visual dummy for the user -->
<input type="checkbox" name="my_name_visual_dummy" value="1" checked="checked" disabled="disabled" />

disabled="disabled" / disabled=true

3
  • 3
    This solves all the issues: creates read-only checkbox, submits POST data and provides visual indication of the read-only-ness (in contrast with all the javascript solutions) Commented Feb 11, 2014 at 16:16
  • 4
    you could also drop off name and value attributes from your dummy-box, also ="checked" and ="diabled" attrib-values could be dropped off. w3.org/TR/html-markup/input.checkbox.html Commented Oct 4, 2014 at 1:18
  • 1
    Most importantly this solution is plain old HTML and doesn't rely on Javascript.
    – GlennG
    Commented Oct 5, 2018 at 16:21
44

This presents a bit of a usability issue.

If you want to display a checkbox, but not let it be interacted with, why even a checkbox then?

However, my approach would be to use disabled (The user expects a disabled checkbox to not be editable, instead of using JS to make an enabled one not work), and add a form submit handler using javascript that enables checkboxes right before the form is submitted. This way you you do get your values posted.

ie something like this:

var form = document.getElementById('yourform');
form.onSubmit = function () 
{ 
    var formElems = document.getElementsByTagName('INPUT');
    for (var i = 0; i , formElems.length; i++)
    {  
       if (formElems[i].type == 'checkbox')
       { 
          formElems[i].disabled = false;
       }
    }
}
8
  • 22
    Another option is to display the disabled checkbox (or an image or anything to denote checked/unchecked) and have a hidden input that is what is processed by the server. Commented Apr 2, 2010 at 15:55
  • 6
    It's not a usability issue when you got a form in which some of your decision affects some other inputs (aka: setting a value that cannot be touched if you don't undo your first action.). I hate when people try to change people's mind instead of answering (this is not about you @FlySwat, you answered). Commented Oct 7, 2010 at 14:01
  • 7
    The purpose is to use a checkbox as a display field "this value is true", which is easier to scan down a table than a bunch of "true"/"false"-s. Sure, you could use an icon but, in a form, checkboxes seem there, ripe for using.
    – Olie
    Commented Aug 13, 2011 at 20:13
  • 1
    I generally use this solution but.. sometimes users, especially on slow connection, see the input buttons enabled after the form submission and decide to play with it. Commented Nov 28, 2012 at 23:00
  • 2
    Suppose you have a series of "features" that can be included or not, so you have a template that shows a check box on the feature. But sometimes, a feature is a prerequisite for something else... so it MUST be included, but you don't want to change your template. That's exactly what a disabled/checked checkbox is for. They've been around forever, so I hope the "why even a checkbox" question was rhetorical.
    – Triynko
    Commented Jan 5, 2016 at 16:12
41
<input type="checkbox" readonly="readonly" name="..." />

with jquery:

$(':checkbox[readonly]').click(function(){
            return false;
        });

it still might be a good idea to give some visual hint (css, text,...), that the control won't accept inputs.

3
  • This didn't work in ie6 for me, the readonly attribute filter doesn't work correctly. I took that out of the filter and put the attribute check in the body of the function and it works fine in ie6.
    – gt124
    Commented Jun 16, 2010 at 17:44
  • 3
    I used "data-readonly=true" instead of the standard attribute and it works fine in all the browsers. I like this solution more then the others above +1 Commented Oct 26, 2012 at 10:20
  • 1
    The selector should be $(':checkbox[readonly]') to select all candidate checkboxes as the readonly attribute value is optional. Commented Dec 16, 2014 at 10:07
34

I would use the readonly attribute

<input type="checkbox" readonly>

Then use CSS to disable interactions:

input[type='checkbox'][readonly]{
    pointer-events: none;
}

Note that using the pseudo-class :read-only doesn't work here.

input[type='checkbox']:read-only{ /*not working*/
    pointer-events: none;
}
5
  • 8
    This is the best answer. But is missing the fact that most checkboxes have an associated label, that will allow the checkbox to be clicked. So in the label do: <label class="form-check-label" for="" title="..." >CBLabel</label> . Notice for="" Moving with the Tab key will work fine too!. Commented Aug 28, 2021 at 15:41
  • 3
    This is best answer by far. Yet to css I would sugest adding label to input too. Like - input[type='checkbox'][readonly], label.form-check-label when you wraping your checkbox wilth label.
    – Saulius
    Commented Oct 15, 2021 at 14:23
  • 4
    I assume this doesn't prevent a keyboard from checking it, though.
    – Roobot
    Commented Jul 6, 2022 at 21:10
  • This doesn't prevent focusing using TAB and hitting SPACE-BAR. Commented Apr 28, 2023 at 14:12
  • To enable wrapping the checkbox in a label, you can add the additional selector, label:has(input[type='checkbox'][readonly]) as the :has() selector is now supported. Commented Jun 7 at 3:27
29

Belated answer, but most answers seem to over complicate it.

As I understand it, the OP was basically wanting:

  1. Readonly checkbox to show status.
  2. Value returned with form.

It should be noted that:

  1. The OP preferred not to use the disabled attribute, because they 'want the checked check boxes to be submitted with the rest of the form'.
  2. Unchecked checkboxes are not submitted with the form, as the quote from the OP in 1. above indicates they knew already. Basically, the value of the checkbox only exists if it is checked.
  3. A disabled checkbox clearly indicates that it cannot be changed, by design, so a user is unlikely to attempt to change it.
  4. The value of a checkbox is not limited to indicating its status, such as yes or false, but can be any text.

Therefore, since the readonly attribute does not work, the best solution, requiring no javascript, is:

  1. A disabled checkbox, with no name or value.
  2. If the checkbox is to be displayed as checked, a hidden field with the name and value as stored on the server.

So for a checked checkbox:

<input type="checkbox" checked="checked" disabled="disabled" />
<input type="hidden" name="fieldname" value="fieldvalue" />

For an unchecked checkbox:

<input type="checkbox" disabled="disabled" />

The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:

<p>Status: Implemented<input type="hidden" name="status" value="implemented" /></p>

1
  • 1
    In the answers chaos of this question, this is the only one. I was about to post it but you did it for me beforehand, thanks. Commented Apr 28, 2023 at 14:06
25

I used this to achieve the results:

<input type=checkbox onclick="return false;" onkeydown="return false;" />
1
  • In my case this works without semicolon, otherwise it doesn't.
    – Mwiza
    Commented Sep 14, 2018 at 7:27
18

Most of the current answers have one or more of these problems:

  1. Only check for mouse not keyboard.
  2. Check only on page load.
  3. Hook the ever-popular change or submit events which won't always work out if something else has them hooked.
  4. Require a hidden input or other special elements/attributes that you have to undo in order to re-enable the checkbox using javascript.

The following is simple and has none of those problems.

$('input[type="checkbox"]').on('click keyup keypress keydown', function (event) {
    if($(this).is('[readonly]')) { return false; }
});

If the checkbox is readonly, it won't change. If it's not, it will. It does use jquery, but you're probably using that already...

It works.

2
  • 2
    This prevents the Tab key from moving off the element once it has focus. Commented Nov 16, 2020 at 20:04
  • Not only does this answer not provide any new approach, it infact actively misinforms the reader! Point 3 Hook the ever-popular change or submit events which won't always work out if something else has them hooked. is plain untrue and probably a symptom of bad code. Additionally, change (maybe not submit) should be the ideal way to handle a change event, not an abuse of click and key* events.
    – bPratik
    Commented Feb 5, 2021 at 11:42
13

I happened to notice the solution given below. In found it my research for the same issue. I don't who had posted it but it wasn't made by me. It uses jQuery:

$(document).ready(function() {
    $(":checkbox").bind("click", false);
});

This would make the checkboxes read only which would be helpful for showing readonly data to the client.

1
  • 1
    The question asks for a readonly checkbox and not a disabled one. So this is most correct answer. Commented Sep 16, 2015 at 15:21
12

This works for me on Chrome:

<input type="checkbox" onclick="return false">
10

If you want them to be submitted to the server with form but be not interacive for user, you can use pointer-events: none in css (works in all modern browsers except IE10- and Opera 12-) and set tab-index to -1 to prevent changing via keyboard. Also note that you can't use label tag as click on it will change the state anyway.

input[type="checkbox"][readonly] {
  pointer-events: none !important;
}

td {
  min-width: 5em;
  text-align: center;
}

td:last-child {
  text-align: left;
}
<table>
  <tr>
    <th>usual
    <th>readonly
    <th>disabled
  </tr><tr>
    <td><input type=checkbox />
    <td><input type=checkbox readonly tabindex=-1 />
    <td><input type=checkbox disabled />
    <td>works
  </tr><tr>
    <td><input type=checkbox checked />
    <td><input type=checkbox readonly checked tabindex=-1 />
    <td><input type=checkbox disabled checked />
    <td>also works
  </tr><tr>
    <td><label><input type=checkbox checked /></label>
    <td><label><input type=checkbox readonly checked tabindex=-1 /></label>
    <td><label><input type=checkbox disabled checked /></label>
    <td>broken - don't use label tag
  </tr>
</table>

5
  • Let me repeat your last sentence (I missed it and wasted precious time): your technique is useless if there's <label> (in Firefox it works perfectly, actually. The issue is with Chrome).
    – Niccolo M.
    Commented Mar 19, 2019 at 5:17
  • @NiccoloM., but if you know that it is readonly, why to wrap it into label? Also you can put label after it and use for attribute. In that case you can use input[type="checkbox"][readonly] + label { pointer-events: none !important; }.
    – Qwertiy
    Commented Mar 19, 2019 at 7:29
  • @KevinBui, have you removed label and added tabindex? How do you set focus on unfocusable element to press a space on it?
    – Qwertiy
    Commented Nov 21, 2019 at 8:32
  • Thanks! This is the only solution I've seen that solves this issue for a Markdown document, where there is no javascript!
    – The Matt
    Commented Oct 7, 2023 at 18:29
  • To enable wrapping the checkbox in a label, you can add the additional selector, label:has(input[type='checkbox'][readonly]) as the :has() selector is now supported. Commented Jun 7 at 3:28
9
onclick="javascript: return false;"
3
  • Hmmm... this is working for the false/unchecked case, but onclick="javascript: return true;" just makes it act like a normal checkbox. Hints? Thanks!
    – Olie
    Commented Aug 13, 2011 at 20:46
  • @Olie, add checked attribute and keep false in place.
    – Qwertiy
    Commented Jun 7, 2019 at 19:10
  • The javascript: scheme is not needed in onclick attributes. Commented Nov 16, 2020 at 20:05
8
<input name="isActive" id="isActive" type="checkbox" value="1" checked="checked" onclick="return false"/>
0
8

No, input checkboxes can't be readonly.

But you can make them readonly with javascript!

Add this code anywhere at any time to make checkboxes readonly work as assumed, by preventing the user from modifying it in any way.

jQuery(document).on('click', function(e){
      // check for type, avoid selecting the element for performance
      if(e.target.type == 'checkbox') {
          var el = jQuery(e.target);
          if(el.prop('readonly')) {
              // prevent it from changing state
              e.preventDefault();
          }
      }
});
input[type=checkbox][readonly] {
    cursor: not-allowed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" checked readonly> I'm readonly!</label>

You can add this script at any time after jQuery has loaded.

It will work for dynamically added elements.

It works by picking up the click event (that happens before the change event) on any element on the page, it then checks if this element is a readonly checkbox, and if it is, then it blocks the change.

This solution should be very efficient and be availble before the page finished loading when the same document click event listener is re-used to handle all the events.

Here's another example using vanilla js

document.addEventListener('click', function(e) {
    // Check if the clicked element is a checkbox
    // Check if the checkbox is read-only
    if (e.target.type === 'checkbox' && e.target.getAttribute('readonly') !== null) {
        // Prevent it from changing state
        e.preventDefault();
    }
});
input[type=checkbox][readonly] {
    cursor: not-allowed;
}
<label><input type="checkbox" checked readonly> I'm readonly!</label>

Keep in mind that according to html5, having a readonly attribute is not strictly valid on an input with type checkbox (despite working in all browsers and search engines don't care), feel free to use data-readonly instead of readonly if you care about that.

5
  • This is the best answer. Calling preventDefault was what I needed. I marked a checkbox as readonly, but clicking it still changed the input's checked value. preventDefault in the input's click callback prevents the checked value from changing.
    – Jake Tyler
    Commented Feb 1 at 16:36
  • Good solution. I'll just add that you can simplify it by passing a selector to the on function: $(document).on("click", "input[type='checkbox'][readonly]", function(e) {e.preventDefault();}); Commented Feb 26 at 3:42
  • @dashingdove That would indeed make the code shorter, but the behaviour would not be the same, what jQuery does if you pass a CSS selector is select all elements that match that selector and then check if the clicked element is in that list of elements, while the code above uses the directly available element directly e.target Commented Jul 4 at 17:56
  • @TimoHuovinen Sorry if I'm misunderstanding but would that not produce the same result? Commented Jul 5 at 9:18
  • @dashingdove depends on what you mean "same result", yes, it will prevent the checking, but something very different happens behind the scenes. If you inspect the jquery source you will see that the second arg for on uses a css selector to select all matching elements and then check if the element being clicked is present in this list, this requires much more effort than jQuery(e.target) which just wraps the element and inspects the already available attributes. Am I explaining it well? Commented Aug 13 at 8:18
6

<input type="checkbox" onclick="return false" /> will work for you , I am using this

0
6

readonly does not work with <input type='checkbox'>

So, if you need to submit values from disabled checkboxes in a form, you can use jQuery:

$('form').submit(function(e) {
    $('input[type="checkbox"]:disabled').each(function(e) {
        $(this).removeAttr('disabled');
    })
});

This way the disabled attributes are removed from the elements when submitting the form.

4

Some of the answers on here seem a bit roundabout, but here's a small hack.

<form id="aform" name="aform" method="POST">
    <input name="chkBox_1" type="checkbox" checked value="1" disabled="disabled" />
    <input id="submitBttn" type="button" value="Submit" onClick='return submitPage();'>
</form>​

then in jquery you can either choose one of two options:

$(document).ready(function(){
    //first option, you don't need the disabled attribute, this will prevent
    //the user from changing the checkbox values
    $("input[name^='chkBox_1']").click(function(e){
        e.preventDefault();
    });

    //second option, keep the disabled attribute, and disable it upon submit
    $("#submitBttn").click(function(){
        $("input[name^='chkBox_1']").attr("disabled",false);
        $("#aform").submit();
    });

});

demo: http://jsfiddle.net/5WFYt/

2
  • 4
    And this isn't "roundabout"??
    – KoZm0kNoT
    Commented Dec 20, 2014 at 1:48
  • nah it's pretty direct.. it's just not concise.
    – sksallaj
    Commented Jan 2, 2015 at 19:29
4

Building on the above answers, if using jQuery, this may be an good solution for all inputs:

<script>
    $(function () {
        $('.readonly input').attr('readonly', 'readonly');
        $('.readonly textarea').attr('readonly', 'readonly');
        $('.readonly input:checkbox').click(function(){return false;});
        $('.readonly input:checkbox').keydown(function () { return false; });
    });
</script>

I'm using this with Asp.Net MVC to set some form elements read only. The above works for text and check boxes by setting any parent container as .readonly such as the following scenarios:

<div class="editor-field readonly">
    <input id="Date" name="Date" type="datetime" value="11/29/2012 4:01:06 PM" />
</div>
<fieldset class="flags-editor readonly">
     <input checked="checked" class="flags-editor" id="Flag1" name="Flags" type="checkbox" value="Flag1" />
</fieldset>
4
<input type="radio" name="alwaysOn" onchange="this.checked=true" checked="checked">
<input type="radio" name="alwaysOff" onchange="this.checked=false" >
0
4

I know that "disabled" isn't an acceptable answer, since the op wants it to post. However, you're always going to have to validate values on the server side EVEN if you have the readonly option set. This is because you can't stop a malicious user from posting values using the readonly attribute.

I suggest storing the original value (server side), and setting it to disabled. Then, when they submit the form, ignore any values posted and take the original values that you stored.

It'll look and behave like it's a readonly value. And it handles (ignores) posts from malicious users. You're killing 2 birds with one stone.

3

I would have commented on ConroyP's answer, but that requires 50 reputation which I don't have. I do have enough reputation to post another answer. Sorry.

The problem with ConroyP's answer is that the checkbox is rendered unchangeable by not even including it on the page. Although Electrons_Ahoy does not stipulate as much, the best answer would be one in which the unchangeable checkbox would look similar, if not the same as, the changeable checkbox, as is the case when the "disabled" attribute is applied. A solution which addresses the two reasons Electrons_Ahoy gives for not wanting to use the "disabled" attribute would not necessarily be invalid because it utilized the "disabled" attribute.

Assume two boolean variables, $checked and $disabled :

if ($checked && $disabled)
    echo '<input type="hidden" name="my_name" value="1" />';
echo '<input type="checkbox" name="my_name" value="1" ',
    $checked ? 'checked="checked" ' : '',
    $disabled ? 'disabled="disabled" ' : '', '/>';

The checkbox is displayed as checked if $checked is true. The checkbox is displayed as unchecked if $checked is false. The user can change the state of the checkbox if and only if $disabled is false. The "my_name" parameter is not posted when the checkbox is unchecked, by the user or not. The "my_name=1" parameter is posted when the checkbox is checked, by the user or not. I believe this is what Electrons_Ahoy was looking for.

1

Very late to the party but I found an answer for MVC (5) I disabled the CheckBox and added a HiddenFor BEFORE the checkbox, so when it is posting if finds the Hidden field first and uses that value. This does work.

 <div class="form-group">
     @Html.LabelFor(model => model.Carrier.Exists, new { @class = "control-label col-md-2" })
         <div class="col-md-10">
              @Html.HiddenFor(model => model.Carrier.Exists)
              @Html.CheckBoxFor(model => model.Carrier.Exists, new { @disabled = "disabled" })
              @Html.ValidationMessageFor(model => model.Carrier.Exists)
          </div>
 </div>
1

If you want ALL your checkboxes to be "locked" so user can't change the "checked" state if "readonly" attibute is present, then you can use jQuery:

$(':checkbox').click(function () {
    if (typeof ($(this).attr('readonly')) != "undefined") {
        return false;
    }
});

Cool thing about this code is that it allows you to change the "readonly" attribute all over your code without having to rebind every checkbox.

It works for radio buttons as well.

1

Extract from https://stackoverflow.com/a/71086058/18183749

If you can't use the 'disabled' attribut (as it erases the value's input at POST), and noticed that html attribut 'readonly' works only on textarea and some input(text, password, search, as far I've seen), and finally, if you don't want to bother with duplicating all your select, checkbox and radio with hidden input logics, you might find the following function or any of his inner logics to your liking :

    addReadOnlyToFormElements = function (idElement) {
        
            // html readonly don't work on input of type checkbox and radio, neither on select. So, a safe trick is to disable the non-selected items
            $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',true); 
     
            // and, on the selected ones, to disable mouse/keyoard events and mimic readOnly appearance
            $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','-1').css('pointer-events','none').css('opacity','0.5');
        }

And there's nothing easier than to remove these readonly

removeReadOnlyFromFormElements = function (idElement) {

    // Remove the disabled attribut on non-selected
    $('#' + idElement + ' input[type="checkbox"]:not(:checked)').prop('disabled',false);

    // Restore mouse/keyboard events and remove readOnly appearance on selected ones
    $('#' + idElement + ' input[type="checkbox"]:checked').prop('tabindex','').css('pointer-events','').css('opacity','');
}
0

I just don't want the client to be able to change them under certain circumstances.

READONLY itself won't work. You may be able to do something funky w/CSS but we usually just make them disabled.

WARNING: If they're posted back then the client can change them, period. You can't rely on readonly to prevent a user from changing something. The could always use fiddler or just chane the html w/firebug or some such thing.

1
  • 1
    You are totally right, that's why i also check that on the server side,setting this is just to improve user experience on the client side.
    – levhita
    Commented Dec 16, 2008 at 21:42
0

The main reason people would like a read-only check-box and (as well) a read-only radio-group is so that information that cannot be changed can be presented back to the user in the form it was entered.

OK disabled will do this -- unfortunately disabled controls are not keyboard navigable and therefore fall foul of all accessibility legislation. This is the BIGGEST hangup in HTML that I know of.

0

Contributing very very late...but anyway. On page load, use jquery to disable all checkboxes except the currently selected one. Then set the currently selected one as read only so it has a similar look as the disabled ones. User cannot change the value, and the selected value still submits.

Not the answer you're looking for? Browse other questions tagged or ask your own question.