Why can't radio buttons be “readonly”?

前端 未结 13 1248
误落风尘
误落风尘 2020-11-27 10:45

I would like to show a radio button, have its value submitted, but depending on the circumstances, have it not editable. Disabled doesn\'t work, because it doesn\'t submit t

13条回答
  •  情歌与酒
    2020-11-27 11:08

    I've come up with a javascript-heavy way to achieve a readonly state for check boxes and radio buttons. It is tested against current versions of Firefox, Opera, Safari, Google Chrome, as well as current and previous versions of IE (down to IE7).

    Why not simply use the disabled property you ask? When printing the page, disabled input elements come out in a gray color. The customer for which this was implemented wanted all elements to come out the same color.

    I'm not sure if I'm allowed to post the source code here, as I developed this while working for a company, but I can surely share the concepts.

    With onmousedown events, you can read the selection state before the click action changes it. So you store this information and then restore these states with an onclick event.

    Option 1
    Option 2
    Option 3
    
    Option 1
    Option 2
    Option 3
    

    The javascript portion of this would then work like this (again only the concepts):

    var selectionStore = new Object();  // keep the currently selected items' ids in a store
    
    function storeSelectedRadiosForThisGroup(elementName) {
        // get all the elements for this group
        var radioOrSelectGroup = document.getElementsByName(elementName);
    
        // iterate over the group to find the selected values and store the selected ids in the selectionStore
        // ((radioOrSelectGroup[i].checked == true) tells you that)
        // remember checkbox groups can have multiple checked items, so you you might need an array for the ids
        ...
    }
    
    function setSelectedStateForEachElementOfThisGroup(elementName) {
        // iterate over the group and set the elements checked property to true/false, depending on whether their id is in the selectionStore
        ...
    
        // make sure you return false here
        return false;
    }
    

    You can now enable/disable the radio buttons/checkboxes by changing the onclick and onmousedown properties of the input elements.

提交回复
热议问题