978

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.

Electrons_Ahoy
  • 36,743
  • 36
  • 104
  • 127
  • 50
    A (malicious) client can always change a checkbox's value (or send arbitrary requests). Always make sure you do proper server-side validation! – knittl Aug 20 '13 at 07: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`) – Christian Gollhardt May 27 '14 at 09:00
  • @ChristianGollhardt: but then, you don't need to send the checkbox' value with the request, since they should be always the initial value. – knittl May 27 '14 at 11:23
  • 5
    @knittl You seem to dismiss the entire sense of `readonly`! Why then this attribute would exist! – Izhar Aazmi Aug 05 '14 at 03: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 Aug 05 '14 at 06: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." – Izhar Aazmi Aug 05 '14 at 09:40
  • @IzharAazmi he was just reminding you. I have bypassed lot of things by editing readonly/disabled or adding custom values in ` – Tomáš Zato Dec 03 '14 at 01:16
  • duplicate of http://stackoverflow.com/questions/12267242/how-can-i-make-a-checkbox-readonly-not-disabled/12267350 – Patrick Lee Scott Jul 05 '16 at 19:22
  • @knittl, checkbox to accept licence agreement when registering on the site. If you don't send it, user can say "hey, I haven't accept it", if you send it, you can check it was checked. But there's no sence in submitting the form with unchecked checkbox. Seems like you may be interested in readonly state in such case. It is there it shoulld be sent and it should be checked. – Qwertiy Mar 05 '19 at 18:38
  • Because I don't often deal with checkboxes, I forget this mess & make the mistake. I had to put an alert into my main js file to remind me if I accidentally do 'readonly' on one. Here it is: ** let cbox = $("input:checkbox"); if ($(cbox).prop('readonly')) { alert("A checkbox CANNOT have readonly property. Please fix!") }; ** – McAuley Oct 04 '19 at 18:05
  • 2
    @knittl Might as well just change it to "why send ANYTHING that you can't edit". Let's forget about sending any static form data becuz we can always write a ton of weird code to tell the server "I didn't receive this field so I must RE-query my database to get the actual value when I'm doing dynamic updates". Seriously, it is what it is -- somebody decided not to provide 'readonly' checkbox for reasons that escape me & most people. Perhaps it involved beer or herbal enhancements. I don't like it becuz it's confusing. A WC3 discussion was underway here: https://github.com/w3c/html/issues/92 – McAuley Oct 04 '19 at 18:19
  • (@)Queertiy. To ensure unequivocal choices, it is best to force selection by using radio buttons. However, best practice would be to force an explicit decision by: 1. Leaving the buttons initially unchecked. 2. If an option has not been selected when submitted, the server code can re-present the page. – Patanjali Feb 04 '20 at 03:02
  • A pretty common occurrence is when you're letting the user edit an already existing piece of data but there are some properties that mustn't be changed any more because this would make some other existing dependent data invalid. It's a better user experience IMHO if the form looks exactly as it did when entering the data in the first place. – MDickten Oct 21 '22 at 08:30

48 Answers48

704

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.

Ahmad Aghazadeh
  • 16,571
  • 12
  • 101
  • 98
Yanni
  • 2,583
  • 2
  • 20
  • 7
  • 1
    Ok, this worked really well for me for the un-checked cases, but how come changing to `..."return true"...` doesn't work? What's the syntax for that? (+1 for half the answer, anyway :) – Olie Aug 13 '11 at 20:40
  • 37
    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 – Jessica Brown Aug 20 '11 at 02:03
  • 10
    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. – Jessica Brown Aug 20 '11 at 02:15
  • 12
    No visual indication of r/o status in this case. – Jesse Glick Mar 13 '13 at 18:58
  • 13
    Prevents from using TAB to navigate to the next input though. – user327961 Apr 29 '13 at 20:57
  • 1
    What purpose does `onkeydown="return false"` serve? Highlighting the field and pressing `space` to toggle its state actually triggers a "click" event, which you've already prevented. `onkeydown` only seems to prevent tabbing away. – mpen Jun 04 '13 at 16:57
  • 1
    Mark is right, skip the keydown and previous comment is not an issue – Yablargo Jul 02 '13 at 01:57
  • 1
    Works great, especially along with setting the checkbox and label `opacity=0.5` so that it looks disabled – Marco Prins Jul 16 '14 at 13:25
  • That's exactly what I was looking for, a "disabled/readonly" behaviour without changing the checkbox style. – David Gras Sep 14 '14 at 00:25
  • 9
    Fails completely if javascript is disabled! – Doin Jun 23 '15 at 10:29
  • Doesn't get checked, but model state change for one time, and inside it self, the model value get changed. – Hassan Faghihi Apr 11 '16 at 12:44
  • This is great for edits where you dont want some properties to be edited but displayed. The disabled="disabled" makes you have to create a hidden input on POST edits where the input has same name as disabled checkbox. – yardpenalty.com Sep 08 '16 at 13:14
  • 3
    a better solution would be `` that way readOnly can be turned on or off at will. – Patrick Denny Feb 22 '17 at 16:39
462

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';
}
Jacek Kowalewski
  • 2,761
  • 2
  • 23
  • 36
ConroyP
  • 40,958
  • 16
  • 80
  • 86
  • 157
    Works, but it's kind of.. well dirty, readonly on checkboxes should simply do what intuition tells. – levhita Dec 16 '08 at 21:41
  • 9
    Intuition fools us, as ConroyP explained. – ANeves May 05 '10 at 18:52
  • 142
    Intuition does not fool US, it fooled those who implemented checkbox this way. – Califf Sep 21 '13 at 15:51
  • @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 Oct 05 '19 at 05: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`. – Niki Romagnoli Apr 28 '23 at 14:09
405

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.

Silvermind
  • 5,791
  • 2
  • 24
  • 44
powtac
  • 40,542
  • 28
  • 115
  • 170
  • 363
    Note that "disabled" checkbox doesn't send value via POST data. – biphobe Sep 20 '11 at 13:56
  • 69
    @powtac You fail to address that he wants the data posted, your example does not do that. – David Mårtensson Feb 08 '12 at 16:59
  • 74
    There is no way this answer should have 105 upvotes. It goes against everything the OP states. – JM4 Dec 12 '12 at 17:18
  • 5
    Why does this answer have so many upvotes? the question clearly states that disabled does not serve the purpose! – Akshay Apr 26 '13 at 11:19
  • 9
    @AkshaySinghal because it serves the purpose for other people that are not the op! – nathan hayfield Jun 07 '13 at 21:22
  • 16
    @nathanhayfield: by that logic, I should be able to post helpful answers about *any* topic and get upvotes. :( – Michael Bray Jul 22 '13 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 Aug 22 '13 at 10:22
  • This corrupts the value - always sends FALSE – Marco Prins Jul 16 '14 at 13:17
  • 1
    Agreed with @JM4, this answer is completely in opposition to the question. May still be useful but -- downvoted :-/ – Cody Sep 12 '14 at 16:17
  • 2
    @JM4 Yes, it should be downvoted, and i use my first downvote, ever, in it! :) (and i don't lose rep?! I guess i can't lose under 125). – Rafael Barros Sep 24 '14 at 20:13
  • Supposedly, you can just add a hidden input (with the value "off" and the same name as the checkbox) right before the checkbox, and it will get submitted when the checkbox doesn't. No JavaScript, just taking advantage of the fact that the last field with a particular name's value will be submitted. It effectively gives you a checkbox that submits a value when unchecked. What a hack HTML is. – Triynko Jan 05 '16 at 16:08
  • 1
    Additional note, just to report it somewhere: it also seems that (at least on Chrome) when the checkbox is disabled then you cannot focus it (that's fine) but you cannot even focus its corresponding ```label```, even adding a ```tabindex="0"``` to it!! (this is not fine) – Kamafeather Jan 06 '16 at 14:41
  • I would like to add that creating a hidden field to allow the value to pass could upset any validation or other scripting expectations in place. If you are expecting a group of checkboxes and interacting with them (looking for their state/value/etc), looking at a HIDDEN field with the same name as the checkboxes means the data/parameters of this control need to be handled independently from the checkboxes. – Gary Richter Mar 10 '16 at 16:00
  • 2
    It got an upvote from me because it's fine for what I need it for - I'm using the checkbox as state on the user-facing page, but the value (if it isn't readonly) already ends up pushed into another field anyway, so I don't care about the value of the checkbox field itself. :) – neminem Aug 17 '17 at 22:48
  • 1
    Sometimes you don't care about the form value(s), for instance if the checkboxes are backed by a `reactive` object, and you are not going to submit any form using form data, but rather the reactive object. – Dexygen Nov 14 '17 at 15:50
  • @GaryRichter. Actually, a `name` attribute is not required for the checkbox. And because an unchecked checkbox doesn't get posted at all, the hidden input should only be used when the checkbox is checked. Also, the value for a checkbox can be any text. See my answer for a complete approach, without misleading appendages! – Patanjali May 27 '19 at 09:06
  • @Patanjali correct, a name attribute isn't required. But the OP originally asked if they can be set to READONLY (which is not a valid attribute of a checkbox) and mentioned they do want the checkbox to be submitted in the form (which means it would need to have a name). The hidden field implementation can be a bit hacky, especially if the user is interacting with a list of checkboxes and not just a single control. My point was this answer may work in a very narrow scope and will create other issues to be taken into consideration depending on the implementation. – Gary Richter May 31 '19 at 13:59
  • 1
    Worked fine in my case. This is the easiest solution to implement in a case where you want the checkbox to be non editable by the user and at the same time send the value to the form. – Dimitris Thomas Nov 15 '21 at 15:44
74
<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.

Grant Wagner
  • 25,263
  • 7
  • 54
  • 64
  • 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 Mar 23 '11 at 18:47
  • This doesnt grey out the boxes as with the answer from powtac so it got my vote – EHarpham Jun 29 '13 at 17:10
  • This is a little hackish, but it is an ingenious, perfect, almost elegant little hack. – russell Dec 02 '13 at 00:50
  • 3
    As stated above, this doesn't work on double clicking in IE. I used: onchange="this.checked=true;" – Ritikesh May 01 '15 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 – Solomon Ucko Nov 05 '16 at 21:39
58

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

shilovk
  • 11,718
  • 17
  • 75
  • 74
summsel
  • 78
  • 2
  • 9
  • 2
    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) – Dalibor Frivaldsky Feb 11 '14 at 16:16
  • 3
    you could also drop off `name` and `value` attributes from your dummy-box, also `="checked"` and `="diabled"` attrib-values could be dropped off. http://www.w3.org/TR/html-markup/input.checkbox.html – Sampo Sarrala - codidact.org Oct 04 '14 at 01:18
  • Most importantly this solution is plain old HTML and doesn't rely on Javascript. – GlennG Oct 05 '18 at 16:21
45

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;
       }
    }
}
FlySwat
  • 172,459
  • 74
  • 246
  • 311
  • 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. – Ruan Mendes Apr 02 '10 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). – Pherrymason Oct 07 '10 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 Aug 13 '11 at 20:13
  • @FlySwat: +1 this to me is the best solution, and it could be used also fo `` fields, see here: http://stackoverflow.com/q/1191113/260080 – Marco Demaio Nov 10 '11 at 11:50
  • 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. – systempuntoout Nov 28 '12 at 23:00
  • +2 for the "why not to use" part, -1 for the code Part = +1 – Christian Gollhardt May 27 '14 at 09:05
  • 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 Jan 05 '16 at 16:12
  • Checkbox feature has been there since before the advent of programming (could be seen in every process flow chart involving decision making) and more so before a windows based interface appeared three decades ago. And they have proved to be visual elixir, almost inalienable part of GUI programming. If I want to tell the user that a particular price was available during a previous period, but is not available now, what better way than to **display a disabled "checked" checkbox**? – Love Putin Not War May 04 '20 at 17:14
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.

John Hascall
  • 9,176
  • 6
  • 48
  • 72
Jan
  • 6,532
  • 9
  • 37
  • 48
  • 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 Jun 16 '10 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 – peipst9lker Oct 26 '12 at 10:20
  • 1
    The selector should be `$(':checkbox[readonly]')` to select all candidate checkboxes as the `readonly` attribute value is optional. – Izhar Aazmi Dec 16 '14 at 10:07
29

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;
}
gordie
  • 1,637
  • 3
  • 21
  • 41
  • 6
    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: . Notice for="" Moving with the Tab key will work fine too!. – Nandostyle Aug 28 '21 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 Oct 15 '21 at 14:23
  • 2
    I assume this doesn't prevent a keyboard from checking it, though. – Roobot Jul 06 '22 at 21:10
  • This doesn't prevent focusing using TAB and hitting SPACE-BAR. – Niki Romagnoli Apr 28 '23 at 14:12
28

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>
Patanjali
  • 893
  • 13
  • 17
  • 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. – Niki Romagnoli Apr 28 '23 at 14:06
25

I used this to achieve the results:

<input type=checkbox onclick="return false;" onkeydown="return false;" />
The Codesee
  • 3,714
  • 5
  • 38
  • 78
Osama Javed
  • 1,432
  • 1
  • 16
  • 21
17

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.

little_birdie
  • 5,600
  • 3
  • 23
  • 28
  • 1
    This prevents the Tab key from moving off the element once it has focus. – Heretic Monkey Nov 16 '20 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 Feb 05 '21 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.

Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
9
onclick="javascript: return false;"
James Parsons
  • 6,097
  • 12
  • 68
  • 108
Sandman
  • 31
  • 1
  • 2
9

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>
Qwertiy
  • 19,681
  • 15
  • 61
  • 128
  • Let me repeat your last sentence (I missed it and wasted precious time): your technique is useless if there's – Niccolo M. Mar 19 '19 at 05: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 Mar 19 '19 at 07:29
  • @KevinBui, have you removed `label` and added `tabindex`? How do you set focus on unfocusable element to press a space on it? – Qwertiy Nov 21 '19 at 08:32
8
<input name="isActive" id="isActive" type="checkbox" value="1" checked="checked" onclick="return false"/>
7

This works for me on Chrome:

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

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

Duke
  • 35,420
  • 13
  • 53
  • 70
5

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.

There are so many ifs to make it not affect the performance of the page.

Timo Huovinen
  • 53,325
  • 33
  • 152
  • 143
5

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.

groovyDynamics
  • 63
  • 1
  • 3
  • 8
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/

sksallaj
  • 3,872
  • 3
  • 37
  • 58
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>
Derrick
  • 2,502
  • 2
  • 24
  • 34
4
<input type="radio" name="alwaysOn" onchange="this.checked=true" checked="checked">
<input type="radio" name="alwaysOff" onchange="this.checked=false" >
frag
  • 415
  • 2
  • 6
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.

NL3294
  • 984
  • 1
  • 10
  • 27
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.

2

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.

Daniel Ribeiro
  • 498
  • 1
  • 4
  • 15
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>
bowlturner
  • 1,968
  • 4
  • 23
  • 35
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

If you need the checkbox to be submitted with the form but effectively read-only to the user, I recommend setting them to disabled and using javascript to re-enable them when the form is submitted.

This is for two reasons. First and most important, your users benefit from seeing a visible difference between checkboxes they can change and checkboxes which are read-only. Disabled does this.

Second reason is that the disabled state is built into the browser so you need less code to execute when the user clicks on something. This is probably more of a personal preference than anything else. You'll still need some javascript to un-disable these when submitting the form.

It seems easier to me to use some javascript when the form is submitted to un-disable the checkboxes than to use a hidden input to carry the value.

Mnebuerquo
  • 5,759
  • 5
  • 45
  • 52
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.

Walden Leverich
  • 4,416
  • 2
  • 21
  • 30
  • 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 Dec 16 '08 at 21:42
0

Or just:

$('your selector').click(function(evt){evt.preventDefault()});
jortsc
  • 308
  • 2
  • 11
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.

Tim
  • 9
  • 1
0

Just use simple disabled tag like this below.

<input type="checkbox" name="email"  disabled>
Nirbhay Rana
  • 4,229
  • 2
  • 18
  • 4
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.

Jason
  • 11
  • 1
-1

If anyone else is using MVC and an editor template, this is how I control displaying a read only property (I use a custom attribute to get the value in the if statement)

@if (true)
{
    @Html.HiddenFor(m => m)
    @(ViewData.Model ? Html.Raw("Yes") : Html.Raw("No"))
} 
else
{               
    @Html.CheckBoxFor(m => m)
}
Richard Maxwell
  • 508
  • 5
  • 7
-1
<input name="testName" type="checkbox" disabled>
Md Rahman
  • 1,812
  • 1
  • 14
  • 15
-1

My solution is actually the opposite of FlySwat's solution, but I'm not sure if it will work for your situation. I have a group of checkboxes, and each has an onClick handler that submits the form (they're used for changing filter settings for a table). I don't want to allow multiple clicks, since subsequent clicks after the first are ignored. So I disable all checkboxes after the first click, and after submitting the form:

onclick="document.forms['form1'].submit(); $('#filters input').each(function() {this.disabled = true});"

The checkboxes are in a span element with an ID of "filters" - the second part of the code is a jQuery statement that iterates through the checkboxes and disables each one. This way, the checkbox values are still submitted via the form (since the form was submitted before disabling them), and it prevents the user from changing them until the page reloads.

sk.
  • 6,336
  • 5
  • 38
  • 46
-1

Latest jQuery has this feature

$("#txtname").prop('readonly', false);
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
Kavi
  • 181
  • 1
  • 6
-1

@(Model.IsEnabled) Use this condition for dynamically check and uncheck and set readonly if check box is already checked.

 <input id="abc" name="abc"  type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >
Tayyeb
  • 127
  • 7
  • 1
    You're using a `Model` object without explaining where it is defined. Also, the answer does not solve the problem, nor provides anything different to any previous posts. I suggest improving the quality and content of this answer, and making it add value. – bPratik Feb 05 '21 at 11:35
-1

When posting an HTML checkbox to the server, it has a string value of 'on' or ''.

Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.
One way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts.

Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.

public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)

    dim strThisCheckedValue

    if (i_strChecked_TorF = "T") then
        strThisCheckedValue = " checked "
        i_strChecked_TorF = "on"
    else
        strThisCheckedValue = ""
        i_strChecked_TorF = ""
    end if

    MakeDummyReadonlyCheckbox = "<input type='hidden' id='" & i_strName & "' name='" & i_strName & "' " & _
        "value='" & i_strChecked_TorF & "'>" & _
    "<input type='checkbox' disabled id='" & i_strName & "Dummy' name='" & i_strName & "Dummy' " & _
        strThisCheckedValue & ">"   
end function

public function GetCheckbox(i_objCheckbox)

    select case trim(i_objCheckbox)

        case ""
            GetCheckbox = "F"

        case else
            GetCheckbox = "T"

    end select

end function

At the top of an ASP page you can pickup the persisted value...

strDataValue = GetCheckbox(Request.Form("chkTest"))

and when you want to output your checkbox you can do this...

response.write MakeDummyReadonlyCheckbox("chkTest", strDataValue)

I have tested this and it works just fine. It also does not rely upon JavaScript.

mskfisher
  • 3,291
  • 4
  • 35
  • 48
  • An unchecked checkbox is ignored when its owning form is posted. There is no variable, let alone a value. – Patanjali May 27 '19 at 08:22
-1

When submitting the form, we actually pass the value of the checkbox, not the state (checked/unchecked). Readonly attribute prevents us to edit the value, but not the state. If you want to have a read-only field that will represent the value you want to submit, use readonly text.

kazinix
  • 28,987
  • 33
  • 107
  • 157
-3

The following works if you know that the checkbox is always checked:

<input type="checkbox" name="Name" checked onchange='this.checked = true;'>
Saiansh Singh
  • 583
  • 5
  • 16
Kamalam
  • 1,254
  • 6
  • 18
  • 32
-3

Simplest (in my view):

onclick="javascript:{this.checked = this.defaultChecked;}"
user493687
  • 11
  • 1
-3

In old HTML you can use

<input type="checkbox" disabled checked>text

but actually is not recommended to use just simply old HTML, now you should use XHTML.

In well formed XHTML you have to use

<input type="checkbox" disabled="disabled" checked="checked" />text <!-- if yu have a checked box-->
<input type="checkbox" disabled="disabled" />text <!-- if you have a unchecked box -->

well formed XHTML requires a XML form, thats the reason to use disabled="disabled" instead of simply use disabled.

fdaines
  • 1,216
  • 10
  • 12
  • But, in this case it will not be submitted in POST array. Sometimes the same behaviour isn't acceptable. – BasTaller Nov 20 '11 at 23:15
-4

What none of you are thinking about here is that you are all using JavaScript, which can be very easily bypassed by any user.

Simply disabling it disables all JQuery/Return False statements.

Your only option for readonly checkboxes is server side.

Display them, let them change them but don't accept the new post data from them.

Stephan
  • 41,764
  • 65
  • 238
  • 329
Ryan
  • 1
-4

You could always use a small image that looks like a check box.

Adam Pierce
  • 33,531
  • 22
  • 69
  • 89
  • 6
    A difficulty with using a picture of a checkbox is that the checkbox itself is drawn by the browser. Some browsers just use the native controls from the OS, but others draw their own stylish controls. So your checkbox picture wouldn't look the same as other checkboxes on the page in some browsers. Of course you could replace all checkboxes on the page with your own style... – Mnebuerquo Sep 26 '09 at 05:38
  • I must admit this is not the worst answer. 7 years passed and HTML still provides no clean and easy way to make readonly checkboxes. Instead of putting tons of javascript which will be disabled by noscript anyway and witchcrafting fake hidden checkboxes you could just remove the checkbox at all and put an image or a text indicating that there is no choice. I also wonder if I'll see any perfect answer on this question before I die from an old age or not. – user619271 Mar 14 '15 at 20:45
-4

Why not cover the input with a blank div on top.

<div id='checkbox_wrap'>
   <div class='click_block'></div>
   <input type='checkbox' /> 
</div>

then something like this with CSS

 #checkbox_wrap{
   height:10px;
   width:10px;
   }
 .click_block{
   height: 10px;
   width: 10px;
   position: absolute;
   z-index: 100;
}
brad
  • 78
  • 5
-4

Try this to make the checkbox read-only and yet disallow user from checking. This will let you POST the checkbox value. You need to select the default state of the checkbox as Checked in order to do so.

<input type="checkbox" readonly="readonly" onclick="this.checked =! this.checked;">

If you want the above functionality + dont want to receive the checkbox data, try the below:

<input type="checkbox" readonly="readonly" disabled="disabled" onclick="this.checked =! this.checked;">

Hope that helps.

Devner
  • 6,825
  • 11
  • 63
  • 104
-5

No, but you might be able to use javascript events to achieve something similar

Mayowa
  • 196
  • 1
  • 5