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','');
}
readonly
)readonly
! Why then this attribute would exist!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 thereadonly
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)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."