HTML required readonly input in form
readonly
fields cannot have the required
attribute, as it's generally assumed that they will already hold some value.
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.
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>
Remove readonly
and use function
<input type="text" name="name" id="id" required onkeypress="return false;" />
It works as you want.