HTML required readonly input in form
Solution 1
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>
Solution 2
readonly
fields cannot have the required
attribute, as it's generally assumed that they will already hold some value.
Solution 3
Remove readonly
and use function
<input type="text" name="name" id="id" required onkeypress="return false;" />
It works as you want.
Solution 4
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.)
Solution 5
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.
![Mathlight](https://i.stack.imgur.com/zuqKa.jpg?s=256&g=1)
Mathlight
Updated on July 23, 2022Comments
-
Mathlight almost 2 years
I'm making a form. And on one
input
tag is anOnClick
event handler, which is opening a popup, where you can choose some stuff, and then it autofills theinput
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?