How can I make an entire HTML form “readonly”?

前端 未结 12 1457
无人及你
无人及你 2020-12-02 07:56

I have two pages with HTML forms. The first page has a submission form, and the second page has an acknowledgement form. The first form offers a choice of many controls, whi

12条回答
  •  难免孤独
    2020-12-02 08:25

    Not all form elements can be set to readonly, for example:

    • checkboxes
    • radio boxes
    • file upload
    • ...more..

    Then the reasonable solution would be to set all form elements' disabled attributes to true, since the OP did not state that the specific "locked" form should be sent to the server (which the disabled attribute does not allow).

    Another solution, which is presented in the demo below, is to place a layer on top of the form element which will prevent any interaction with all the elements inside the form element, since that layer is set with a greater z-index value:

    DEMO:

    var form = document.forms[0], // form element to be "readonly"
        btn1 = document.querySelectorAll('button')[0],
        btn2 = document.querySelectorAll('button')[1]
    
    btn1.addEventListener('click', lockForm)
    btn2.addEventListener('click', lockFormByCSS)
    
    function lockForm(){
      btn1.classList.toggle('on');
      [].slice.call( form.elements ).forEach(function(item){
          item.disabled = !item.disabled;
      });
    }
    
    function lockFormByCSS(){
      btn2.classList.toggle('on');
      form.classList.toggle('lock');
    }
    form{ position:relative; } 
    form.lock::before{
      content:'';
      position:absolute;
      z-index:999;
      top:0;
      right:0;
      bottom:0;
      left:0;
    }
    
    button.on{ color:red; }
    
    
    

    Some Form









提交回复
热议问题