简体   繁体   English

如何在提交时导航禁用html表单?

[英]How to disable html form from navigating on submit?

Lets say I have this form 可以说我有这种形式

<form onsubmit="submitData();">
    <input type="text" pattern="^[A-z]+$" required>
    <button type="submit">OK</button>
</form>

Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. 单击提交按钮后,我不希望表单在地址栏中发布任何数据或导航到任何地方,我只是希望它运行submitData函数,就是这样。 The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern). 我想使用表单的原因是因为它的验证功能(如果输入文本丢失或与模式不匹配,它不会让你提交)。

If I switch the value of onsubmit on the form to "return false;" 如果我将窗体上onsubmit的值切换为“return false;” then it won't navigate but "submitData(); return false;" 那么它不会导航但是“submitData();返回false;” doesn't work. 不起作用。 Any other ideas? 还有其他想法吗?

Try adding e.preventDefault(); 尝试添加e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) { , like this: 在代码的开头,将事件传递给function submitData(e) { ,如下所示:

function submitData(e) {
    e.preventDefault();
    ...
}

See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault 请参阅: https//developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Just add event.preventDefault that is automatically pass by the form to the function: 只需将表单自动传递的event.preventDefault添加到函数中:

function submitData(event){
   event.preventDefault();    
   //your code will be here
}

read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault 阅读更多: https//developer.mozilla.org/en/docs/Web/API/Event/preventDefault

Use event.preventDefault() . 使用event.preventDefault()

Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault 了解更多信息: https//developer.mozilla.org/en/docs/Web/API/Event/preventDefault

add this to your code: 将此添加到您的代码中:

document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
        event.preventDefault()
    });

or this in your function: 或者你的功能:

function submitData(event) {
    event.preventDefault();

}

You'd want to cancel the default action of the submit event handler, so: 您想要取消提交event处理程序的默认操作 ,因此:

function submitData() {
    // whatever logic you have...
    return false;
}

I believe this works too: 我相信这也有效:

function submitData( e ) {
    e.preventDefault();
    // whatever logic you have...
}

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

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