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