即使未填写必填字段,我也可以在超时时提交表格



我想知道是否可以在一定时间段(例如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>

当然,只需将此逻辑放入函数中即可。您只需从字段中删除required属性。

let form = document.querySelector('form');
let inputs = form.getElementsByTagName('input');
let i;
for (i = 0; i < inputs.length; i++) {
inputs[i].required = false;
}

您的代码有几个问题:

  1. 您不应该打开和关闭br标记,您只需要在需要换行符的位置放置一个<br>
  2. autofocus属性应该只放在一个输入上,并且当页面加载时,该输入将具有焦点
  3. 根据调用代码的方式,可能会遇到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>

我把暂停时间改为一秒钟,只是为了能够看到效果。

相关内容

最新更新