Creating readonly HTML checkbox and still have its value submitted


There are two ways for preventing changes of HTML form elements values. One can either set readonly="readonly" or disabled="disabled". Those two have only one difference - when form with readonly element is submitted, the element data is present in the POST body. On the other hand a disabled element is not present in POST body as if this element weren't there.

And here's the little catch with checkbox elements: they are subclass of input elements and when set to readonly only prevent changes to the value attribute. This however does nothing for checking of unchecking them. When set to disabled checkbox state is locked, but a disabled checked checkbox is not included in POST data and thus cannot be used. Here's a little Javascript workaround for this - every time user clicks on the checkbox, it's state is negated and thus reverted to the state before the click:

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

 

Comments:

Atul (16-08-2011 13:35) :
nice trick

Rodrigo (21-11-2012 14:22) :
Does not work!
When faster clicked the value changes.

Nick Genova (27-03-2015 16:54) :
Worked great for me! Thanks!

Back to articles list

This page was last modified on 2024-04-24 21:40:00