Javascript 如何防止表单被提交?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3350247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:16:46  来源:igfitidea点击:

How to prevent form from being submitted?

javascripthtmlforms

提问by Nathan Osman

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.

我无法修改提交按钮,因为它是自定义控件的一部分。

回答by Ben Rowe

Unlike the other answers, return falseis only partof the answer. Consider the scenario in which a JS error occurs prior to the return statement...

与其他答案不同,返回false只是答案的一部分。考虑在 return 语句之前发生 JS 错误的场景......

html

html

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

script

脚本

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

returning falsehere won't be executed and the form will be submitted either way. You should also call preventDefaultto prevent the default form action for Ajax form submissions.

返回false这里不会被执行,表单将以任何一种方式提交。您还应该调用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...catchblock could be used.

或者,try...catch可以使用块。

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

回答by Reigel

You can use inline event onsubmitlike 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. For I can not explain it more than Chris Bakerdid.

在此处阅读有关内联事件与事件侦听器(addEventListener 和 IE 的 attachEvent)的更多信息。因为我无法比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.

两者都是正确的,但它们本身都不是“最好的”,开发人员选择使用这两种方法可能是有原因的。

回答by Micha? Per?akowski

Attach an event listener to the form using .addEventListener()and then call the .preventDefault()method on event:

使用.addEventListener()以下.preventDefault()方法将事件侦听器附加到表单,然后调用方法event

const element = document.querySelector('form');
element.addEventListener('submit', event => {
  event.preventDefault();
  // actual logic, e.g. 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 submitevent handler inline with the onsubmitattribute because it separates webpage logic and structure. It's much easier to maintain a project where logic is separated from HTML. See: Unobtrusive JavaScript.

我认为这是一个比定义一个submitonsubmit属性内联的事件处理程序更好的解决方案,因为它分离了网页逻辑和结构。维护逻辑与 HTML 分离的项目要容易得多。请参阅:不显眼的 JavaScript

Using the .onsubmitproperty of the formDOM object is not a good idea because it prevents you from attaching multiple submit callbacks to one element. See addEventListener vs onclick .

使用DOM 对象的.onsubmit属性form不是一个好主意,因为它会阻止您将多个提交回调附加到一个元素。请参阅addEventListener 与 onclick

回答by Sach

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.");
    });
});

回答by Vikram Pudi

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 falseif validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault()

其中 validateMyForm() 是一个函数,false如果验证失败则返回。关键点是使用名称event。我们不能用于例如e.preventDefault()

回答by naikus

var form = document.getElementById("idOfForm");
form.onsubmit = function() {
  return false;
}

回答by naikus

To follow unobtrusive JavaScriptprogramming conventions, and depending on how quickly the DOMwill 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 ready 连接事件。

$(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 actionattribute as some people may have some plugin like NoScriptrunning which would then break the validation. If you're using the action attribute, at the very least your user will get redirected by the server based on the backend validation. If you're using something like window.location, on the other hand, things will be bad.

另外,我总是会使用该action属性,因为有些人可能会运行一些像NoScript这样的插件,这会破坏验证。如果您使用 action 属性,至少您的用户将根据后端验证被服务器重定向。window.location另一方面,如果你使用类似的东西,事情会很糟糕。

回答by Zuhair Taha

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.

通过使用上面的代码,这将阻止您提交表单。

回答by yozawiratama

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();on onsubmitand it works.

我想补充event.preventDefault();onsubmit和它的作品。

回答by Hasan A Yousef

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>