Javascript requestSubmit() 的替代方法。由于safari不支持

Javascript alternative for requestSubmit(). Since safari does not support it

我正在尝试使用 Javascript 提交我的表单。通过单击按钮或按回车键。 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 事件(保存按钮)中使用 document.getElementById('HoursForm').dispatchEvent(new Event('submit'));。但这只会触发提交事件。并且不提交表单或验证字段(例如 minmax 属性被跳过)。

.submit()确实提交了表单,但没有触发提交事件。使用户能够向按钮发送垃圾邮件并多次提交表单。

那么,我需要的是:

好的,我已经修好了。

我改了几行:

// Added dispatch event AND submit(); I previously only used one of them.
<button id="SaveButton" type="button" class="..." onclick="document.getElementById('HoursForm').dispatchEvent(new Event('submit')); document.hours.submit();">Opslaan</button>

在 Javascript 中我将 .requestSubmit() 更改为 .submit()。并添加了dispatch event来触发事件。

/**
 * When pressed enter, next part of form should be shown or form should be submitted. Also a little `&&` in my if statement to validate the form.
 * 
 * @param {Event} e 
 */
 function submitFormWithEnter(e) {
    if (e.key === 'Enter') {

        // If the next button is visible, trigger the next part. Else if the save button is visible trigger the submitform part. 
        if (!nextButton.classList.contains('d-none')) {
            nextForm();
        } else if (!kmPrivateField.classList.contains('d-none') && hoursForm.reportValidity()) {

            // Submit form.
            hoursForm.dispatchEvent(new Event('submit'));
            hoursForm.submit();
        }
    }
}

这帮我修好了。