一起使用 required 和 readonly 属性

Using required and readonly attributes together

我正在创建一个 HTML5 网络表单。输入之一用于地理定位,通过单击按钮(它插入 gps 坐标)来填充。由于此输入必须是必需的并且必须是只读的(我不希望用户在其中写入自定义数据),因此如何处理? HTML5 不允许使用 requiredreadonly(这是有道理的),但在我的情况下我需要应用它。您知道任何解决方法吗?

我在 SO 和 Google 上搜索了又搜索,但 none 似乎知道解决方案。

这是我的部分代码:

    <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>

使用 event.preventDefault(); 防止默认行为。

不能是 keydown,只需将其挂在您要点击的事件中...

不要忘记将 "event" 添加到函数调用中,这样就可以了。

<input type="text" class="readonly" required />

<script>
    $(".readonly").keydown(function(e){
        e.preventDefault();
    });
</script>
<input type="text" name="name" id="id" required onkeypress="return false;" />

在此 textBox 中,用户不能输入任何内容,只能输入 required 以及 readonly