71

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??

4
  • 1
    Duplicate here: stackoverflow.com/questions/155291/… Commented Sep 4, 2012 at 16:03
  • this is not working for me....thats the problem..I am using <s:iterator> and retrieving status value in action class... here is the code for that <c:choose> <c:when test="#divisionCdSid.first == true"> <s:iterator value="divisionList" status="divisionCdSid" id="entity"> <input type="checkbox" name="divisionCdSid" id="exportDivision" value="<s:property value="sid"/>" checked onclick="return false" onkeydown="return false"/> <s:property value="divsionNm" /> </s:iterator> </c:when> <c:otherwise> Commented Sep 4, 2012 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. Commented Sep 4, 2012 at 16:20
  • 1
    Possible duplicate of Can HTML checkboxes be set to readonly? Commented Sep 21, 2017 at 12:53

16 Answers 16

136

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

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

DEMO

Sign up to request clarification or add additional context in comments.

6 Comments

I tried but not working..When I click on the checkbox its getting unchecked
@Naga, You can see the demo its working correctly. I have added the demo in my answer.
Nice trick so that I don't need to create some dummmmmmy field together with hidden field.
Works with keyboard navigation, too (tab to it, hit spacebar).
Excellent answer.
|
43
<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/

5 Comments

Thanks.. It worked now..Its because of the if case that caused problem.. Thanks
This stops you being able to tab through the elements @MRodrigues answer is a better solution
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.
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 stackoverflow.com/a/41486636/1091926
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 jsfiddle.net/founddrama/eKSuj
40

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

6 Comments

This doesn't prevent ticking of the checkbox via the keyboard (tab to the checkbox, and hit spacebar).
For preventing ticking of the checkbox via the keyboard, please use Patrick's answer at stackoverflow.com/a/12267350/1091926
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; }
@jtheletter, just need to add tab-index="-1"
The best solution of century
|
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.

Comments

10

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

2 Comments

this is not working for me....thats the problem..I am using <s:iterator> and retrieving status value in action class... here is the code for that <c:choose> <c:when test="#divisionCdSid.first == true"> <s:iterator value="divisionList" status="divisionCdSid" id="entity"> <input type="checkbox" name="divisionCdSid" id="exportDivision" value="<s:property value="sid"/>" checked onclick="checkStatusSid();" onkeydown="return false"/> <s:property value="divsionNm" /> </s:iterator> </c:when> <c:otherwise>
@Naga - nothing stops you from onclick="checkStatusSid(); return false;" But if onkeydown="return false;" works for you - than why not?
6

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

1 Comment

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.
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")

1 Comment

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; }
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.

Comments

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;">

Comments

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.

Comments

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; }

Comments

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;
        }
    }
});

Comments

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','');
}

Comments

0

I know this is an old question, but there's a situation no one has addressed yet that was causing me problems.

I've tried all these options and some work, while some don't work. And none of them worked when there's a label for that checkbox. The current version of Chrome seems to bypass all of this and still changes the checkbox when the label is clicked. Or maybe it's a jQuery thing, I'm not 100% sure.

The one thing that did work in this instance is setting the label to have a class that included pointer-events: none;, which then prevented the click event on the label and also whatever was happening to cause the checkbox to change.

Comments

-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/

2 Comments

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, it will if: 1. remove label tag; 2. add tabindex attribute - that's not a style.
-4
document.getElementById("your checkbox id").disabled=true;

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.