简体   繁体   English

通过javascript提交HTML表单并防止默认

[英]Submit an HTML form by javascript and prevent default

i am using a virtual keyboard built with javascript for a user interface running on an embedded system.我正在使用用 javascript 构建的虚拟键盘作为在嵌入式系统上运行的用户界面。

Source code for the virtual keyboard can be found here : https://codepen.io/dcode-software/pen/KYYKxP虚拟键盘的源代码可以在这里找到: https : //codepen.io/dcode-software/pen/KYYKxP

I only changed a single part in the source code.我只更改了源代码中的一个部分。 Keyboard.js file line 141-151: Keyboard.js 文件第 141-151 行:

case "enter":
          keyElement.classList.add("keyboard__key--wide");
          keyElement.innerHTML = createIconHTML("Enter");

          keyElement.addEventListener("click", () => {
            this.properties.value += "\n";
            this._triggerEvent("oninput");
            /**
             * The part that i modified
             */
            document.querySelector("form").submit();
          });

          break;

Basically, what I'm trying to do here is to submit the form on the current page when the "enter" key is pressed on the virtual keyboard.基本上,我在这里尝试做的是在虚拟键盘上按下“回车”键时提交当前页面上的表单。 (Which works fine) (哪个工作正常)

But i also want to prevent default on this submit event.但我也想阻止这个提交事件的默认值。 ( e.preventDefault() ) So how can i achieve that? ( e.preventDefault() ) 那么我该如何实现呢? Thanks for your help.谢谢你的帮助。

Edit : I already added e.preventDefault() to the submit function.编辑:我已经将e.preventDefault()添加到提交函数中。 Here is the code which i handle the login form submit:这是我处理登录表单提交的代码:

//Login
const loginForm = document.querySelector("#login-form");
loginForm.addEventListener("submit", async (e) => {
  e.preventDefault();

  const errorContainer = document.querySelector("#login-form-message");

  errorContainer.innerHTML = "";

  try {
    //Submitting form
  } catch (error) {
    //Handle error
  }
});

I found it after reading the MDN documentation.我是在阅读 MDN 文档后找到的。

This is the HTMLFormElement.submit() documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit这是HTMLFormElement.submit()文档: https : //developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

This document explains quite well why I have this problem.这份文件很好地解释了为什么我会遇到这个问题。

To summarize, I need to use the requestSubmit () function instead of the submit () function since the submit() function does not trigger a submit event.总而言之,我需要使用requestSubmit ()函数而不是submit ()函数,因为submit()函数不会触发submit事件。

HTMLFormElement.requestSubmit() documentation: https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit HTMLFormElement.requestSubmit()文档: https : //developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM