HTML required readonly input in form

Mathlight picture Mathlight · Oct 8, 2012 · Viewed 67.8k times · Source

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?

Answer

Kanak Singhal picture Kanak Singhal · Sep 6, 2014

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>