How can I make a checkbox readonly? not disabled?

JavascriptCheckbox

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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

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

DEMO

Solution 2 - Javascript

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

Solution 3 - Javascript

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

Solution 4 - Javascript

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.

Solution 5 - Javascript

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

Solution 6 - Javascript

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

Solution 7 - Javascript

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

Solution 8 - Javascript

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.

Solution 9 - Javascript

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.

Solution 10 - Javascript

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

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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

Solution 14 - Javascript

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/

Solution 15 - Javascript

document.getElementById("your checkbox id").disabled=true;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNagaView Question on Stackoverflow
Solution 1 - JavascriptKundan Singh ChouhanView Answer on Stackoverflow
Solution 2 - JavascriptPatrick Lee ScottView Answer on Stackoverflow
Solution 3 - JavascriptAleXView Answer on Stackoverflow
Solution 4 - JavascriptMRodriguesView Answer on Stackoverflow
Solution 5 - JavascriptViktor S.View Answer on Stackoverflow
Solution 6 - JavascriptLuca C.View Answer on Stackoverflow
Solution 7 - Javascriptuser1170104View Answer on Stackoverflow
Solution 8 - JavascriptAntonio OoiView Answer on Stackoverflow
Solution 9 - JavascriptEricView Answer on Stackoverflow
Solution 10 - JavascriptGary KlasenView Answer on Stackoverflow
Solution 11 - Javascriptyoussef115View Answer on Stackoverflow
Solution 12 - JavascriptDinkhellerView Answer on Stackoverflow
Solution 13 - Javascriptvincent salomonView Answer on Stackoverflow
Solution 14 - JavascriptAnton EfremenkovView Answer on Stackoverflow
Solution 15 - JavascripttinylcyView Answer on Stackoverflow