HTML required readonly input in form

后端 未结 13 2057
执笔经年
执笔经年 2020-12-13 08:36

I\'m making a form. And on one input tag is an OnClick event handler, which is opening a popup, where you can choose some stuff, and then it autofi

相关标签:
13条回答
  • 2020-12-13 09:35

    This is by design. According to the official HTML5 standard drafts, "if the readonly attribute is specified on an input element, the element is barred from constraint validation." (E.g. its values won't be checked.)

    0 讨论(0)
  • 2020-12-13 09:35

    Yes, there is a workaround for this issue. I found it from https://codepen.io/fxm90/pen/zGogwV site.

    Solution is as follows.

    HTML File

    <form>
      <input type="text" value="" required data-readonly />
      <input type="submit" value="Submit" />
    </form>
    

    CSS File

    input[data-readonly] {
      pointer-events: none;
    }
    
    0 讨论(0)
  • 2020-12-13 09:39

    If anyone wants to do it only from html, This works for me.

    <input type="text" onkeydown="event.preventDefault()" required />
    
    0 讨论(0)
  • 2020-12-13 09:39

    Required and readonly don't work together.

    Although you can make two inputs like this:

    <input id="One" readonly />
    <input id="Two" required style="display: none" /> //invisible
    

    And change the value Two to the value that´s inside the input One.

    0 讨论(0)
  • 2020-12-13 09:40

    I think this should help.

    <form onSubmit="return checkIfInputHasVal()">
        <input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();"  />
    </form>
    
    <script>
         function checkIfInputHasVal(){
            if($("#formAfterRederict").val==""){
                 alert("formAfterRederict should have a value");
                 return false;
            }
         }
    </script>
    
    0 讨论(0)
  • 2020-12-13 09:42

    I had same requirement as yours and I figured out an easy way to do this. If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jquery this way:

    <input type="text" class="readonly" required />
    
    <script>
        $(".readonly").keydown(function(e){
            e.preventDefault();
        });
    </script>
    

    EDIT

    as @Ed Bayiates pointed in the comment you can also add paste handler to preventDefault like this:

    <input type="text" class="readonly" required />
    
    <script>
        $(".readonly").on('keydown paste', function(e){
            e.preventDefault();
        });
    </script>
    
    0 讨论(0)
提交回复
热议问题