【问题标题】:Can I submit form on timeout even if required fields are not filled即使未填写必填字段,我是否可以在超时时提交表单
【发布时间】:2020-10-28 04:48:46
【问题描述】:
我想知道是否可以在一段时间(例如 2 分钟)后提交表单,即使未填写所有必填字段,因为我希望在该固定时间段内输入所有数据要提交。目前,虽然我使用的是基于 javascript 的超时功能,但它不允许在超时时提交表单,因为未完成必填字段。我将所有字段设置为必填,因为如果它不是必填字段,则自动对焦功能似乎不起作用(即在当前字段中按 enter 后不会自动进入下一个输入字段。有没有办法解决这个问题?谢谢非常感谢您的帮助!
window.setTimeout(() => this.submit(), 120000)
<html>
<main>
<form>
<br><label for="response1"><b>Animals</b></label><br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus required></br>
<br><input type="text" id="response2" name="response2" autocomplete="off" autofocus required></br>
<br><input type="text" id="response3" name="response3" autocomplete="off" autofocus required></br>
<br><input type="text" id="response4" name="response4" autocomplete="off" autofocus required></br>
<button type="submit">Submit</button>
</form>
</main>
</html>
【问题讨论】:
标签:
javascript
html
form-submit
required
【解决方案1】:
当然,只需将此逻辑放入您的函数中即可。您只需从字段中删除 required 属性即可。
let form = document.querySelector('form');
let inputs = form.getElementsByTagName('input');
let i;
for (i = 0; i < inputs.length; i++) {
inputs[i].required = false;
}
【解决方案2】:
您的代码有几个问题:
- 你不应该打开和关闭 br 标签,你只需在你想要换行的地方放一个
<br>
- autofocus 属性只能放在一个输入上,并且该输入将在页面加载时获得焦点。
- 根据您调用代码的方式,您可能会遇到
this 关键字的问题,最好直接调用表单。
我在您的代码中更改了这些内容并成功使用了以下代码(无需删除所需的属性,但如果确实不需要它们,只需删除它们):
window.setTimeout(() => document.forms[0].submit(), 1000)
<html>
<main>
<form>
<br>
<label for="response1">
<b>Animals</b>
</label>
<br>
<input type="text" id="response1" name="response1" autocomplete="off" autofocus required>
<br>
<input type="text" id="response2" name="response2" autocomplete="off" required>
<br>
<input type="text" id="response3" name="response3" autocomplete="off" required>
<br>
<input type="text" id="response4" name="response4" autocomplete="off" required>
<button type="submit">Submit</button>
</form>
</main>
</html>
为了能看到效果,我把超时时间改成了一秒。