Search code examples
htmlbuttononclickreadonlyrequired

Using required and readonly attributes together


I'm creating an HTML5 web form. One of the inputs is for geolocation and it is filled by clicking on a button (it inserts gps coordinates). Since this input has to be required and has to be read-only (i do not want that users write custom data inside), how to handle this? HTML5 does not allow to use required and readonly (and this makes sense), but in my case i need to apply it. Do you know any workaround?

I searched and searched here on SO and on Google, but none seems to know a solution.

Here is a part of my code:

    <form class="form-horizontal" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        <div class="form-group">
            <label class="control-label col-xs-3" for="coord">GPS coordinates:*</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="coord" name="coord" required placeholder="Please enable geolocation service">
            </div>
            <div class="col-xs-3">
                <button type="button" onclick="getLocation()" class="btn btn-primary" id="locate" disabled>Locate me</button>
            </div>
        </div>

Solution

  • Use event.preventDefault(); to prevent default behavior.

    must not be keydown just hang it to your event you are calling on click...

    don't forget to add the "event" to the functions call, so you have it there.

    <input type="text" class="readonly" required />
    
    <script>
        $(".readonly").keydown(function(e){
            e.preventDefault();
        });
    </script>