59

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 autofills the input tag.

That input tag is also readonly, so only right data will be entered.

This is the code of the input tag:

<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();"  />

But the required attribute isn't working in Chrome. But the field is required.

Does anybody know how I can make it work?

user2428118
  • 7,935
  • 4
  • 45
  • 72
Mathlight
  • 6,436
  • 17
  • 62
  • 107

14 Answers14

115

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:

IMPROVED

form the suggestions in comments

<input type="text" class="readonly" autocomplete="off" required />

<script>
    $(".readonly").on('keydown paste focus mousedown', function(e){
        if(e.keyCode != 9) // ignore tab
            e.preventDefault();
    });
</script>

Credits: @Ed Bayiates, @Anton Shchyrov, @appel, @Edhrendal, @Peter Lenjo

ORIGINAL

<input type="text" class="readonly" required />

<script>
    $(".readonly").keydown(function(e){
        e.preventDefault();
    });
</script>
Kanak Singhal
  • 3,074
  • 1
  • 19
  • 17
  • 5
    I also added a paste handler to preventDefault, and the solution was complete! – Ed Bayiates Sep 10 '15 at 20:11
  • 5
    Good answer, but his blocked **ALL** keys (included Tab, Left, Right) and not blocked `Cut` event. I wrote self version :) – Anton Shchyrov Apr 18 '17 at 21:27
  • Thanks a lot! @Kanak your answer was useful for me. – Carmoreno May 16 '17 at 20:44
  • Please note that this solution doesn't quite work for number inputs. You can still use the arrow keys to change input. – appel Dec 15 '17 at 18:09
  • 1
    The fix for number input is adding a 'mousedown' handler. – appel Dec 15 '17 at 18:17
  • @appel, in my case I needed the mouse click event, but I could use type="text" with pattern="[0-9]*". Anyway its a nice catch worth pointing out. thanks – Kanak Singhal Dec 15 '17 at 18:41
  • @KanakSinghal Gotcha! I needed mine to be `type="number"` so I could use `min="100"` and `required` and have client side validation work (which it will not with the `readonly` attribute). – appel Dec 15 '17 at 22:48
  • Beware the autocompletion. Add `autocomplete="off"` on the input or with jQuery: `$(".readonly").attr("autocomplete", "off")` or `$(".readonly").prop("autocomplete", "off")` for jQuery >=1.6. – Edhrendal Jul 03 '19 at 14:24
  • 2
    I added the focus handler to avoid autocomplete and showing the cursor. – Peter Mghendi Feb 01 '20 at 13:37
34

readonly fields cannot have the required attribute, as it's generally assumed that they will already hold some value.

BenM
  • 52,573
  • 26
  • 113
  • 168
  • 2
    And you don't know an work around? because i want to check it before the form is realy submitted... – Mathlight Oct 08 '12 at 08:27
  • @TWCrap if your input field is read only how do you suppose your user gonna enter any value in that ?? – yogi Oct 08 '12 at 08:28
  • 2
    @yogi, if you readed the question right, then you saw that i use on OnClick event handler that will popup something that sends an value back... – Mathlight Oct 08 '12 at 08:29
  • 1
    Well, aside from making some validation to ensure that the value is only one of those you are entering using your JS, there's little you can do. Also, I'd recommend using `onfocus`, for the use of tabs on your form. – BenM Oct 08 '12 at 08:32
  • 1
    @yogi with a datepicker modal . . . – ajbraus Jul 21 '14 at 17:27
  • 2
    Yeah datepicker modal is the obvious use case, `readonly` because it's the only way to stop a mobile device's keyboard popping up unnecessarily. – Rob Grant Jun 05 '15 at 10:13
26

Remove readonly and use function

<input type="text" name="name" id="id" required onkeypress="return false;" />

It works as you want.

Parth Patel
  • 799
  • 1
  • 13
  • 20
21

Required and readonly don't work together.

But readonly can be replaced with following construction:

     <input     type="text"
                onkeydown="return false;"
                style="caret-color: transparent !important;"                   
                required>

1) onkeydown will stop manipulation with data

2) style="caret-color: transparent !important;" will hide cursor.

3) you can add style="pointer-events: none;" if you don't have any events on your input, but it was not my case, because I used a Month Picker. My Month picker is showing a dialog on click.

Yevgeniy Afanasyev
  • 37,872
  • 26
  • 173
  • 191
16

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.)

user2428118
  • 7,935
  • 4
  • 45
  • 72
9

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;
}
Udara Seneviratne
  • 2,303
  • 1
  • 33
  • 49
7

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

<input type="text" onkeydown="event.preventDefault()" required />
Shabbir
  • 273
  • 4
  • 7
1

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>
scireon
  • 365
  • 2
  • 4
  • 17
1

You can do this for your template:

<input required onfocus="unselect($event)" class="disabled">

And this for your js:

unselect(event){
    event.preventDefault();
    event.currentTarget.blur();
}

For a user the input will be disabled and required at the same time, providing you have a css-class for disabled input.

Alex Link
  • 1,210
  • 13
  • 16
1

Based on answer @KanakSinghal but without blocked all keys and with blocked cut event

$('.readonly').keydown(function(e) {
  if (e.keyCode === 8 || e.keyCode === 46)  // Backspace & del
    e.preventDefault();
}).on('keypress paste cut', function(e) {
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="readonly" value="test" />

P.S. Somebody knows as cut event translate to copy event?

Anton Shchyrov
  • 285
  • 3
  • 15
1

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.

Deadpool
  • 210
  • 3
  • 14
0

I have the same problem, and finally I use this solution (with jQuery):

form.find(':input[required][readonly]').filter(function(){ return this.value === '';})

In addition to the form.checkValidity(), I test the length of the above search somehow this way:

let fcnt = $(form)
    .find(':input[required][readonly]')
    .filter(function() { return this.value === '';})
    .length;

if (form.checkValidity() && !fcnt) {
   form.submit();
}
CsZsombor
  • 69
  • 1
  • 4
-1

  function validateForm() {
    var x = document.forms["myForm"]["test2"].value;
    if (x == "") {
      alert("Name missing!!");
      return false;
    }
  }
  <form class="form-horizontal" onsubmit="return validateForm()" name="myForm" action="" method="POST">
   <input type="text"  name="test1">
    <input type="text" disabled name="test2">
    <button type="submit">Submit</button>
</form>
  • Some explanation to support your answer please. Code only answers are not very educational. – Gnqz Aug 03 '17 at 16:05
-1

It's the best solution for me. The client can not type anything and must be filled

<input type="text" class="read-only" required>
.read-only {
         pointer-events: none;
 }
Melisa
  • 310
  • 2
  • 16