简体   繁体   English

如何防止表单被提交?

[英]How to prevent form from being submitted?

I have a form that has a submit button in it somewhere.我有一个表单,其中某处有一个提交按钮。

However, I would like to somehow 'catch' the submit event and prevent it from occurring.但是,我想以某种方式“捕捉”提交事件并防止它发生。

Is there some way I can do this?有什么办法可以做到这一点吗?

I can't modify the submit button, because it's part of a custom control.我无法修改提交按钮,因为它是自定义控件的一部分。

Unlike the other answers, return false is only part of the answer.与其他答案不同,return false只是答案的一部分 Consider the scenario in which a JS error occurs prior to the return statement...考虑在 return 语句之前发生 JS 错误的场景......

html html

<form onsubmit="return mySubmitFunction(event)">
  ...
</form>

script脚本

function mySubmitFunction()
{
  someBug()
  return false;
}

returning false here won't be executed and the form will be submitted either way.此处返回false将不会被执行,并且表单将以任何一种方式提交。 You should also call preventDefault to prevent the default form action for Ajax form submissions.您还应该调用preventDefault来阻止 Ajax 表单提交的默认表单操作。

function mySubmitFunction(e) {
  e.preventDefault();
  someBug();
  return false;
}

In this case, even with the bug the form won't submit!在这种情况下,即使有错误,表单也不会提交!

Alternatively, a try...catch block could be used.或者,可以使用try...catch块。

function mySubmit(e) { 
  e.preventDefault(); 
  try {
   someBug();
  } catch (e) {
   throw new Error(e.message);
  }
  return false;
}

You can use inline event onsubmit like this您可以像这样使用内联事件onsubmit

<form onsubmit="alert('stop submit'); return false;" >

Or或者

<script>
   function toSubmit(){
      alert('I will not submit');
      return false;
   }
</script>

<form onsubmit="return toSubmit();" >

Demo演示

Now, this may be not a good idea when making big projects.现在,在制作大型项目时,这可能不是一个好主意。 You may need to use Event Listeners.您可能需要使用事件侦听器。

Please read more about Inline Events vs Event Listeners (addEventListener and IE's attachEvent) here .在此处阅读有关内联事件与事件侦听器(addEventListener 和 IE 的 attachEvent)的更多信息 For I can not explain it more than Chris Baker did.因为我无法比Chris Baker解释得更多。

Both are correct, but none of them are "best" per se, and there may be a reason the developer chose to use both approaches.两者都是正确的,但它们本身都不是“最好的”,开发人员选择使用这两种方法可能是有原因的。

Attach an event listener to the form using .addEventListener() and then call the .preventDefault() method on event :使用 .addEventListener() 将事件侦听器附加到表单,然后在event上调用.addEventListener() .preventDefault()方法:

 const element = document.querySelector('form'); element.addEventListener('submit', event => { event.preventDefault(); // actual logic, eg validate the form console.log('Form submission cancelled.'); });
 <form> <button type="submit">Submit</button> </form>

I think it's a better solution than defining a submit event handler inline with the onsubmit attribute because it separates webpage logic and structure.我认为这是一个比定义与onsubmit属性内联的submit事件处理程序更好的解决方案,因为它分离了网页逻辑和结构。 It's much easier to maintain a project where logic is separated from HTML.维护逻辑与 HTML 分离的项目要容易得多。 See: Unobtrusive JavaScript .请参阅:不显眼的 JavaScript

Using the .onsubmit property of the form DOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element.使用form DOM 对象的.onsubmit属性不是一个好主意,因为它会阻止您将多个提交回调附加到一个元素。 See addEventListener vs onclick .请参阅addEventListener 与 onclick

The following works as of now (tested in chrome and firefox):以下作品截至目前(在 chrome 和 firefox 中测试):

<form onsubmit="event.preventDefault(); return validateMyForm();">

where validateMyForm() is a function that returns false if validation fails.其中 validateMyForm() 是一个在验证失败时返回false的函数。 The key point is to use the name event .关键点是使用名称event We cannot use for eg e.preventDefault()我们不能使用例如e.preventDefault()

Try this one...试试这个...

HTML Code HTML 代码

<form class="submit">
    <input type="text" name="text1"/>
    <input type="text" name="text2"/>
    <input type="submit" name="Submit" value="submit"/>
</form>

jQuery Code jQuery 代码

$(function(){
    $('.submit').on('submit', function(event){
        event.preventDefault();
        alert("Form Submission stopped.");
    });
});

or或者

$(function(){
    $('.submit').on('submit', function(event){
       event.preventDefault();
       event.stopPropagation();
       alert("Form Submission prevented / stopped.");
    });
});
var form = document.getElementById("idOfForm");
form.onsubmit = function() {
  return false;
}

For prevent form from submittion you only need to do this.为了防止表单提交,您只需要这样做。

<form onsubmit="event.preventDefault()">
    .....
</form>

By using above code this will prevent your form submittion.通过使用上面的代码,这将阻止您的表单提交。

To follow unobtrusive JavaScript programming conventions, and depending on how quickly the DOM will load, it may be a good idea to use the following:为了遵循不显眼的 JavaScript编程约定,并根据DOM加载的速度,使用以下内容可能是个好主意:

<form onsubmit="return false;"></form>

Then wire up events using the onload or DOM ready if you're using a library.如果您正在使用库,则使用 onload 或 DOM 准备好连接事件。

 $(function() { var $form = $('#my-form'); $form.removeAttr('onsubmit'); $form.submit(function(ev) { // quick validation example... $form.children('input[type="text"]').each(function(){ if($(this).val().length == 0) { alert('You are missing a field'); ev.preventDefault(); } }); }); });
 label { display: block; } #my-form > input[type="text"] { background: cyan; }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id="my-form" action="http://google.com" method="GET" onsubmit="return false;"> <label>Your first name</label> <input type="text" name="first-name"/> <label>Your last name</label> <input type="text" name="last-name" /> <br /> <input type="submit" /> </form>

Also, I would always use the action attribute as some people may have some plugin like NoScript running which would then break the validation.另外,我总是使用action属性,因为有些人可能会运行一些像NoScript这样的插件,这会破坏验证。 If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation.如果您使用 action 属性,至少您的用户将被服务器基于后端验证重定向。 If you're using something like window.location , on the other hand, things will be bad.另一方面,如果您使用类似window.location的东西,情况会很糟糕。

You can add eventListner to the form, that preventDefault() and convert form data to JSON as below:您可以将 eventListner 添加到表单中,即preventDefault()并将表单数据转换为 JSON,如下所示:

 const formToJSON = elements => [].reduce.call(elements, (data, element) => { data[element.name] = element.value; return data; }, {}); const handleFormSubmit = event => { event.preventDefault(); const data = formToJSON(form.elements); console.log(data); // const odata = JSON.stringify(data, null, " "); const jdata = JSON.stringify(data); console.log(jdata); (async () => { const rawResponse = await fetch('/', { method: 'POST', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: jdata }); const content = await rawResponse.json(); console.log(content); })(); }; const form = document.forms['myForm']; form.addEventListener('submit', handleFormSubmit);
 <form id="myForm" action="/" method="post" accept-charset="utf-8"> <label>Checkbox: <input type="checkbox" name="checkbox" value="on"> </label><br /><br /> <label>Number: <input name="number" type="number" value="123" /> </label><br /><br /> <label>Password: <input name="password" type="password" /> </label> <br /><br /> <label for="radio">Type: <label for="a">A <input type="radio" name="radio" id="a" value="a" /> </label> <label for="b">B <input type="radio" name="radio" id="b" value="b" checked /> </label> <label for="c">C <input type="radio" name="radio" id="c" value="c" /> </label> </label> <br /><br /> <label>Textarea: <textarea name="text_area" rows="10" cols="50">Write something here.</textarea> </label> <br /><br /> <label>Select: <select name="select"> <option value="a">Value A</option> <option value="b" selected>Value B</option> <option value="c">Value C</option> </select> </label> <br /><br /> <label>Submit: <input type="submit" value="Login"> </label> <br /><br /> </form>

<form v-on:submit.prevent="yourMethodHere">

The submit event will no longer reload the page.提交事件将不再重新加载页面。 It runs your method.它运行你的方法。

From vue documentation: https://vuejs.org/guide/essentials/event-handling.html#event-modifiers来自 vue 文档: https ://vuejs.org/guide/essentials/event-handling.html#event-modifiers

Here my answer :这是我的答案:

<form onsubmit="event.preventDefault();searchOrder(event);">
...
</form>
<script>
const searchOrder = e => {
    e.preventDefault();
    const name = e.target.name.value;
    renderSearching();

    return false;
}
</script>

I add event.preventDefault();我添加event.preventDefault(); on onsubmit and it works.onsubmit上,它可以工作。

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

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