66

I have a form where I have to post form values to my action class. In this form I have a checkbox that needs to be readonly. I tried setting disabled="true" but that doesn't work when posting to the action class.

So please advice??

c0deNinja
  • 3,956
  • 1
  • 29
  • 45
Naga
  • 812
  • 2
  • 8
  • 12
  • 1
    Duplicate here: http://stackoverflow.com/questions/155291/can-html-checkboxes-be-set-to-readonly – Ben McCormick Sep 04 '12 at 16:03
  • this is not working for me....thats the problem..I am using and retrieving status value in action class... here is the code for that " checked onclick="return false" onkeydown="return false"/> – Naga Sep 04 '12 at 16:18
  • could you please edit the original question and put the code there in code format (tabbed out 4 spaces) its unreadable in the comment. Thanks. – Ben McCormick Sep 04 '12 at 16:20
  • 1
    Possible duplicate of [Can HTML checkboxes be set to readonly?](https://stackoverflow.com/questions/155291/can-html-checkboxes-be-set-to-readonly) – Denilson Sá Maia Sep 21 '17 at 12:53

15 Answers15

126

There is no property to make the checkbox readonly. But you can try this trick.

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

DEMO

Kundan Singh Chouhan
  • 13,952
  • 4
  • 27
  • 32
42
<input type="checkbox" checked onclick="return false;" onkeydown="return false;"/>

http://jsfiddle.net/2srjc/

If you are worried about tab order, only return false for the keydown event when the tab key was not pressed:

<input type="checkbox" checked onclick="return false;" onkeydown="e = e || window.event; if(e.keyCode !== 9) return false;"/>

http://jsfiddle.net/2srjc/149/

Patrick Lee Scott
  • 8,217
  • 3
  • 36
  • 42
  • 2
    Thanks.. It worked now..Its because of the if case that caused problem.. Thanks – Naga Sep 04 '12 at 16:30
  • 1
    This stops you being able to tab through the elements @MRodrigues answer is a better solution – 99 Problems - Syntax ain't one Jun 30 '16 at 14:40
  • For readonly, your supposed to be able to tab through the checkboxes but not be able to change the value with the space bar. Neither of these solutions does that. – CodeWarrior Jun 22 '18 at 15:07
  • On Mac/Safari, the checkbox can still trigger a "change" event in jQuery if the checkbox itself is clicked. To prevent triggering such jQuery event, please also implement AleX's answer at https://stackoverflow.com/a/41486636/1091926 – Wayne Liu Jul 16 '18 at 23:47
  • Along with the above correct answer , if you want to set the css as for it to show it as disabled use following jsfiddle example https://jsfiddle.net/founddrama/eKSuj/ – Aditya Sep 06 '21 at 06:46
36

You can easily do this by css. HTML :

<form id="aform" name="aform" method="POST">
    <input name="chkBox_1" type="checkbox" checked value="1" readonly />
    <br/>
    <input name="chkBox_2" type="checkbox" value="1" readonly />
    <br/>
    <input id="submitBttn" type="button" value="Submit">
</form>

CSS :

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

Demo

Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
AleX
  • 399
  • 3
  • 10
  • 16
    This doesn't prevent ticking of the checkbox via the keyboard (tab to the checkbox, and hit spacebar). – 2540625 Jan 10 '17 at 04:19
  • For preventing ticking of the checkbox via the keyboard, please use Patrick's answer at https://stackoverflow.com/a/12267350/1091926 – Wayne Liu Jul 16 '18 at 23:41
  • 2
    If the checkbox is followed by a label (which is also clickable), we may also add this CSS: input[type="checkbox"][readonly] + label { pointer-events: none; } – Wayne Liu Jul 16 '18 at 23:42
  • @jtheletter, just need to add `tab-index="-1"` – Qwertiy Mar 05 '19 at 18:40
  • The best solution of century – Rifton007 Sep 16 '20 at 18:01
  • does not prevent the box from being clicked on with the mouse in chrome and the field read by php as clicked or unclicked. Functionally it does nothing to change the behavior of the field. – Debbie Kurth Feb 24 '21 at 18:57
16

I personally like to do it this way:

<input type="checkbox" name="option" value="1" disabled="disabled" />
<input type="hidden" name="option" value="1">

I think this is better for two reasons:

  1. User clearly understand that he can't edit this value
  2. The value is sent when submitting the form.
2540625
  • 11,022
  • 8
  • 52
  • 58
MRodrigues
  • 1,927
  • 1
  • 17
  • 22
9

You may simply add onclick="return false" - this will stop browser executing default action (checkbox checked/not checked will not be changed)

Viktor S.
  • 12,736
  • 1
  • 27
  • 52
  • this is not working for me....thats the problem..I am using and retrieving status value in action class... here is the code for that " checked onclick="checkStatusSid();" onkeydown="return false"/> – Naga Sep 04 '12 at 16:17
  • @Naga - nothing stops you from onclick="checkStatusSid(); return false;" But if onkeydown="return false;" works for you - than why not? – Viktor S. Sep 04 '12 at 16:34
5

Make a fake checkbox with no name and value, force the value in an hidden field:

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

Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name

Luca C.
  • 11,714
  • 1
  • 86
  • 77
  • 1
    This answer is better than the accepted answer because it prevents changing the checkbox using the keyboard. One slight improvement would be to use CSS to prevent the gray color that comes with disabling a checkbox. It should stay black. – CodeWarrior Jun 22 '18 at 14:59
3

I use JQuery so I can use the readonly attribute on checkboxes.

//This will make all read-only check boxes truly read-only
$('input[type="checkbox"][readonly]').on("click.readonly", function(event){event.preventDefault();}).css("opacity", "0.5");

If you want the checkbox to be editable again then you need to do the following for the specific checkbox.

$('specific checkbox').off('.readonly').removeAttr("readonly").css("opacity", "1")
  • This solved my problem nicely, although I did it on document because I'm dynamically loading in elements on the page and I don't have to unbind the event when I remove the attribute: $(document).on('click', 'input[type="checkbox"][readonly]', function (event) { event.preventDefault(); }); I also added a style rather than adding the opacity with JQuery input[type='checkbox'][readonly]{ opacity: 0.5; } – GavKilbride May 31 '16 at 07:27
3

If you say 'No' to the following:

  1. disable=true because other functionalities may not work, such as form posting.
  2. onclick='return false' because other events may still trigger the change, such as keyup, keydown when on focus.
  3. e.preventDefault()
  4. CSS: pointer-events: none; because you may want to allow change under certain conditions.

Then just do this in the change event of your read-only checkbox:

$("#chkReadOnly").on("change", function () {
   // Enclose with 'if' statement if conditional.
   // Simply restore back the default value, i.e. true.
   $(this).prop("checked", true);
});

This will solve all the above problems.

Antonio Ooi
  • 1,601
  • 1
  • 18
  • 32
1

In my case, i only needed it within certain conditions, and to be done easily in HTML:

<input type="checkbox" [style.pointer-events]="(condition == true) ? 'none' : 'auto'"> 

Or in case you need this consistently:

<input type="checkbox" style="pointer-events: none;">
Gary Klasen
  • 1,001
  • 1
  • 12
  • 30
0

None of the above worked for me. Here's my vanilla.js solution:

(function() {
    function handleSubmit(event) {
        var form = event.target;
        var nodes = form.querySelectorAll("input[disabled]");
        for (var node of nodes) {
            node.disabled = false;
        }
    }

    function init() {
        var submit_form_tag = document.getElementById('new_whatever');
        submit_form_tag.addEventListener('submit', handleSubmit, true);
    }

    window.onload = init_beworst;

})();

Be sure to provide an appropriate replacement for the form id.

My application has a bit of context, where some boxes are pre-checked, and others you have a limit of how many of the other boxes you can check. When you hit that limit, all the non-pre-checked boxes are disabled, and if you uncheck one all the non-pre-checked boxes are enabled again. When the user presses submit all the checked boxes are submitted to the user, regardless of whether they're pre-checked or not.

Eric
  • 2,115
  • 2
  • 20
  • 29
0

You can't do it directly, but you can do it with this way I try it, and it's work fine with me at the same time it is so simple

HTML :

<input type="checkbox" checked disabled="true" class="style" />

CSS :

.style{ opacity: 1; }

youssef115
  • 37
  • 6
0

Here is my solution (override) for Sencha ExtJS 7.2+ (checkbox and radio in a single override)


Ext.define('MyApp.override.field.Checkbox', {
    override: 'Ext.field.Checkbox',

    /**
     * OVERRIDE: to allow updateReadOnly to work propperly
     * @param {boolean} newValue
     *
     * To ensure the disabled state stays active if the field is still readOnly
     * we re - set the disabled state
     */
    updateDisabled(newValue) {
        this.callParent(arguments);

        if (!newValue && this.getReadOnly()) {
            this.inputElement.dom.disabled = true;
        }
    },

    /**
     * OVERRIDE: readonly for radiogroups and checkboxgroup do not work as other fields
     *     https://stackoverflow.com/questions/1953017/why-cant-radio-buttons-be-readonly
     *
     * @param {boolean} newValue
     *
     *  - use disabled on the field
     */
    updateReadOnly(value) {
        this.callParent(arguments);

        if (!this.getDisabled()) {
            this.inputElement.dom.disabled = value;
        }
    }
});
Dinkheller
  • 4,631
  • 5
  • 39
  • 67
0

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, 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 deactivate mouse/keyboard 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','');
}
-1

Through CSS:

<label for="">
  <input type="checkbox" style="pointer-events: none; tabindex: -1;" checked> Label
</label>

pointer-events not supported in IE<10

https://jsfiddle.net/fl4sh/3r0v8pug/2/

  • 1
    That is what the accepted answer from back in January said. As pointed out in the comments, it doesn't prevent people from checking it with the keyboard. – Quentin Dec 08 '17 at 10:29
  • @Quentin, it will if: 1. remove `label` tag; 2. add `tabindex` attribute - that's not a style. – Qwertiy Mar 05 '19 at 18:42
-3
document.getElementById("your checkbox id").disabled=true;
tinylcy
  • 37
  • 4
  • `I tried setting disabled="true" but that doesn't work when posting to the action class.` - OP is looking for a solution that does not depend on the `disabled` attr – Don Cheadle Apr 04 '16 at 16:33