Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 781
smartmouse Avatar asked Dec 10 '22 23:12

smartmouse


2 Answers

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>
like image 84
Timotheus0106 Avatar answered Dec 30 '22 17:12

Timotheus0106


<input type="text" name="name" id="id" required onkeypress="return false;" />

In this textBox user can not input anything but input is required and also readonly.

like image 36
Parth Patel Avatar answered Dec 30 '22 19:12

Parth Patel