【发布时间】:2022-01-13 15:20:12
【问题描述】:
我正在尝试使用 Javascript 提交我的表单。通过单击按钮或按 Enter 键。 type="submit" 通常会完成所有这些工作。问题是我有一个“下一步”按钮,它应该激活一个显示表单下一部分的功能。所以我使用以下代码提交我的表单:
// Form:
<form name="hours" method="post" id="HoursForm" class="form">
// nextForm() goes to next part in form.
<button id="NextButton" type="button" class="..." onclick="nextForm()">Next</button>
<button id="SaveButton" type="button" class="..." onclick="document.hours.requestSubmit();">Save</button>
保存按钮将触发我的事件监听器,它执行以下操作:
hoursForm.addEventListener("submit", function() {
// If form is submitted and valid, remove the ability to submit again.
window.removeEventListener('keyup', submitFormWithEnter, false);
saveButton.disabled = true;
});
当用户按下“进入”按钮时,将触发“下一步”或“保存”功能。
/**
* When pressed enter, next part of form should be shown or form should be submitted.
*
* @param {Event} e
*/
function submitFormWithEnter(e) {
if (e.key === 'Enter') {
// If the next button is visible, trigger the next part. Else if the last part of the form is visible, submit the form.
if (!nextButton.classList.contains('d-none')) {
nextForm();
} else if (!kmPrivateField.classList.contains('d-none')) {
// Submit form.
hoursForm.requestSubmit();
}
}
}
所以在我们使用 safari 之前一切正常。 如MDN 所示。这个功能有替代品吗?
我尝试在我的onclick 事件(SaveButton)中使用document.getElementById('HoursForm').dispatchEvent(new Event('submit'));。但这只会触发提交事件。并且不提交表单或验证字段(例如,min、max 属性被跳过)。
.submit() 会提交表单,但不会触发提交事件。使用户能够向按钮发送垃圾邮件并多次提交表单。
那么,我需要什么:
- 随时点击“保存”按钮提交表单。
- 使用“enter”键提交表单,但仅在表单末尾(最后一页/部分)时。
- 使用户只能提交一次表单。单击按钮或使用“输入”按钮保存表单后,禁用提交功能。
- 支持几乎所有常见的浏览器,除了 IE。例如。 this is fine。
【问题讨论】:
标签: javascript html forms onclick form-submit