// user allowed changeif($user_allowed_edit){echo '<input type="checkbox" name="my_check"> Check value';}else{// Not allowed change - submit value..echo '<input type="hidden" name="my_check" value="1" />';// .. and show user the value being submittedecho '<input type="checkbox" disabled readonly> Check value';}
var form = document.getElementById('yourform');form.onSubmit = function (){var formElems = document.getElementsByTagName('INPUT');for (var i = 0; i , formElems.length; i++){if (formElems[i].type == 'checkbox'){formElems[i].disabled = false;}}}
<input type="checkbox" disabled="disabled" checked="checked" />text <!-- if yu have a checked box--><input type="checkbox" disabled="disabled" />text <!-- if you have a unchecked box -->
$(document).ready(function(){//first option, you don't need the disabled attribute, this will prevent//the user from changing the checkbox values$("input[name^='chkBox_1']").click(function(e){e.preventDefault();});
//second option, keep the disabled attribute, and disable it upon submit$("#submitBttn").click(function(){$("input[name^='chkBox_1']").attr("disabled",false);$("#aform").submit();});
});
<!-- field that holds the data --><input type="hidden" name="my_name" value="1" /><!-- visual dummy for the user --><input type="checkbox" name="my_name_visual_dummy" value="1" checked="checked" disabled="disabled" />
jQuery(document).on('click', function(e){// check for type, avoid selecting the element for performanceif(e.target.type == 'checkbox') {var el = jQuery(e.target);if(el.prop('readonly')) {// prevent it from changing statee.preventDefault();}}});
The main problem with disabled inputs, especially checkboxes, is their poor contrast which may be a problem for some with certain visual disabilities. It may be better to indicate a value by plain words, such as Status: none or Status: implemented, but including the hidden input above when the latter is used, such as:
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');}
没有什么比删除这些只读更容易的了
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','');}