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

前端 未结 12 1402
无人及你
无人及你 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:13

    There's no fully compliant, official HTML way to do it, but a little javascript can go a long way. Another problem you'll run into is that disabled fields don't show up in the POST data

    0 讨论(0)
  • 2020-12-02 08:14

    I'd rather use jQuery:

    $('#'+formID).find(':input').attr('disabled', 'disabled');
    

    find() would go much deeper till nth nested child than children(), which looks for immediate children only.

    0 讨论(0)
  • 2020-12-02 08:17

    Easiest way

    $('#yourform *').prop('readonly', true);
    
    0 讨论(0)
  • 2020-12-02 08:19

    Another simple way that's supported by all browsers would be:

    HTML:

    <form class="disabled">
      <input type="text" name="name" />
      <input type="radio" name="gender" value="male">
      <input type="radio" name="gender" value="female">
      <input type="checkbox" name="vegetarian">
    </form>
    

    CSS:

    .disabled {
      pointer-events: none;
      opacity: .4;
    }
    

    But be aware, that the tabbing still works with this approach and the elements with focus can still be manipulated by the user.

    0 讨论(0)
  • 2020-12-02 08:20

    This is an ideal solution for disabling all inputs, textareas, selects and buttons in a specified element.

    For jQuery 1.6 and above:

    // To fully disable elements
    $('#myForm :input').prop('disabled', true); 
    

    Or

    // To make elements readonly
    $('#myForm :input').prop('readonly', true); 
    

    jQuery 1.5 and below:

    $('#myForm :input').prop('disabled', 'disabled');
    

    And

    $('#myForm :input').prop('readonly', 'readonly');
    
    0 讨论(0)
  • 2020-12-02 08:24

    Wrap the input fields and other stuff into a <fieldset> and give it the disabled="disabled" attribute.

    Example (http://jsfiddle.net/7qGHN/):

    <form>
        <fieldset disabled="disabled">
            <input type="text" name="something" placeholder="enter some text" />
            <select>
                <option value="0" disabled="disabled" selected="selected">select somethihng</option>
                <option value="1">woot</option>
                <option value="2">is</option>
                <option value="3">this</option>
            </select>
        </fieldset>
    </form>

    0 讨论(0)
提交回复
热议问题