简体   繁体   English

如何防止按钮提交 forms

[英]How to prevent buttons from submitting forms

In the following page, with Firefox the remove button submits the form, but the add button does not.在接下来的页面中,对于 Firefox,删除按钮提交表单,但添加按钮不提交。

How do I prevent the remove button from submitting the form?如何防止remove按钮提交表单?

 function addItem() { var v = $('form:hidden:last').attr('name'); var n = /(.*)input/.exec(v); var newPrefix; if (n[1].length == 0) { newPrefix = '1'; } else { newPrefix = parseInt(n[1]) + 1; } var oldElem = $('form tr:last'); var newElem = oldElem.clone(true); var lastHidden = $('form:hidden:last'); lastHidden.val(newPrefix); var pat = '=\"' + n[1] + 'input'; newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input')); newElem.appendTo('table'); $('form:hidden:last').val(''); } function removeItem() { var rows = $('form tr'); if (rows.length > 2) { rows[rows.length - 1].html(''); $('form:hidden:last').val(''); } else { alert('Cannot remove any more rows'); } }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <html> <body> <form autocomplete="off" method="post" action=""> <p>Title:<input type="text" /></p> <button onclick="addItem(); return false;">Add Item</button> <button onclick="removeItem(); return false;">Remove Last Item</button> <table> <th>Name</th> <tr> <td><input type="text" id="input1" name="input1" /></td> <td><input type="hidden" id="input2" name="input2" /></td> </tr> </table> <input id="submit" type="submit" name="submit" value="Submit"> </form> </body> </html>

You're using an HTML5 button element.您正在使用 HTML5 按钮元素。 Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button请记住,原因是此按钮具有提交的默认行为,如 W3 规范中所述,如下所示: W3C HTML5 按钮

So you need to specify its type explicitly:所以你需要明确指定它的类型:

<button type="button">Button</button>

in order to override the default submit type.为了覆盖默认提交类型。 I just want to point out the reason why this happens.我只想指出发生这种情况的原因。

Set the type on your buttons:在按钮上设置类型:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

...that'll keep them from triggering a submit action when an exception occurs in the event handler. ...这将防止他们在事件处理程序中发生异常时触发提交操作。 Then, fix your removeItem() function so that it doesn't trigger an exception:然后,修复您的removeItem()函数,使其不会触发异常:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.请注意更改:您的原始代码从 jQuery 集中提取了一个 HTML 元素,然后尝试对其调用 jQuery 方法 - 这引发了异常,导致按钮的默认行为。

FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front: FWIW,您可以使用另一种方法...使用 jQuery 连接您的事件处理程序,并使用 jQuery事件对象上的preventDefault()方法预先取消默认行为:

$(function() // execute once the DOM has loaded
{

  // wire up Add Item button click event
  $("#AddItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
  });

  // wire up Remove Last Item button click event
  $("RemoveLastItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of remove last logic
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript .这种技术将您的所有逻辑保存在一个地方,使其更易于调试......它还允许您通过更改按钮上的type来实现回退以submit和处理事件服务器端 - 这是已知的作为不显眼的 JavaScript

Sometime ago I needed something very similar... and I got it.前段时间我需要一些非常相似的东西......我得到了它。

So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).所以我在这里介绍的是我如何使用技巧使表单能够通过 JavaScript 提交而无需任何验证,并且仅在用户按下按钮(通常是发送按钮)时执行验证。

For the example I will use a minimal form, only with two fields and a submit button.对于示例,我将使用一个最小的表单,只有两个字段和一个提交按钮。

Remember what is wanted: From JavaScript it must be able to be submitted without any checking.记住需要什么:从 JavaScript 必须能够在没有任何检查的情况下提交。 However, if the user presses such a button, the validation must be done and form sent only if pass the validation.但是,如果用户按下这样的按钮,则必须完成验证,并且只有通过验证才能发送表单。

Normally all would start from something near this (I removed all extra stuff not important):通常一切都会从这个附近的东西开始(我删除了所有不重要的额外内容):

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>

See how form tag has no onsubmit="..." (remember it was a condition not to have it).看看表单标签是如何没有onsubmit="..."的(记住它是没有它的条件)。

The problem is that the form is always submitted, no matter if onclick returns true or false .问题是表单总是被提交,无论onclick返回true还是false

If I change type="submit" for type="button" , it seems to work but does not.如果我将type="submit"更改为type="button" ,它似乎工作但没有。 It never sends the form, but that can be done easily.它从不发送表单,但这很容易完成。

So finally I used this:所以最后我用了这个:

<form method="post" id="theFormID" name="theFormID" action="">
   <input type="text" id="Field1" name="Field1" />
   <input type="text" id="Field2" name="Field2" />
   <input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>

And on function Validator , where return True;function Validator上, return True; is, I also add a JavaScript submit sentence, something similar to this:是,我还添加了一个 JavaScript 提交语句,类似于以下内容:

function Validator(){
   //  ...bla bla bla... the checks
   if(                              ){
      document.getElementById('theFormID').submit();
      return(true);
   }else{
      return(false);
   }
}

The id="" is just for JavaScript getElementById , the name="" is just for it to appear on POST data. id=""仅适用于 JavaScript getElementByIdname=""仅适用于它出现在 POST 数据中。

On such way it works as I need.以这种方式,它可以按我的需要工作。

I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.我只为那些不需要在表单上提交onsubmit功能,但在用户按下按钮时进行一些验证的人。

Why I need no onsubmit on form tag?为什么我不需要在表单标签上提交? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.很简单,在其他 JavaScript 部分我需要执行提交,但我不希望有任何验证。

The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.原因:如果用户是执行我想要的提交并且需要完成验证的用户,但如果是 JavaScript,有时我需要执行提交,而这样的验证会避免它。

It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!这听起来可能很奇怪,但在思考时却不是这样:在登录时……有一些限制……比如不允许使用 PHP 会话,也不允许使用 cookie!

So any link must be converted to such form submit, so the login data is not lost.所以任何链接都必须转换成这样的表单提交,这样登录数据才不会丢失。 When no login is yet done, it must also work.当尚未完成登录时,它也必须工作。 So no validation must be performed on links.因此,不必对链接执行验证。 But I want to present a message to the user if the user has not entered both fields, user and pass.但是,如果用户没有输入用户和通行证这两个字段,我想向用户显示一条消息。 So if one is missing, the form must not be sent!因此,如果缺少一个,则不得发送该表格! there is the problem.有问题。

See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.看到问题:只有当用户按下按钮时,一个字段为空时才不能发送表单,如果它是 JavaScript 代码,则必须能够发送。

If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript.如果我在表单标签上进行onsubmit工作,我需要知道它是用户还是其他 JavaScript。 Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not.由于不能传参数,所以不能直接传,所以有人加了一个变量来判断是否必须做验证。 First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.验证功能的第一件事是检查变量值等......太复杂了,代码并没有说明真正想要什么。

So the solution is not to have onsubmit on the form tag.所以解决方案是不要在表单标签上设置 onsubmit。 Insead put it where it really is needed, on the button. Insead 把它放在了真正需要的地方,就在按钮上。

For the other side, why put onsubmit code since conceptually I do not want onsubmit validation.另一方面,为什么要放置 onsubmit 代码,因为从概念上讲我不想要 onsubmit 验证。 I really want button validation.我真的想要按钮验证。

Not only the code is more clear, it is where it must be.不仅代码更清晰,而且它必须在哪里。 Just remember this: - I do not want JavaScript to validate the form (that must be always done by PHP on the server side) - I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)请记住这一点: - 我不希望 JavaScript 验证表单(必须始终由服务器端的 PHP 完成) - 我想向用户显示一条消息,告诉所有字段不能为空,需要 JavaScript(客户端边)

So why some people (think or tell me) it must be done on an onsumbit validation?那么为什么有些人(想或告诉我)必须在现场验证上完成? No, conceptually I am not doing a onsumbit validating at client side.不,从概念上讲,我没有在客户端进行 onsumbit 验证。 I am just doing something on a button get pressed, so why not just let that to be implemented?我只是在按下按钮上做某事,那么为什么不让它实现呢?

Well that code and style does the trick perfectly.好吧,代码和样式完美地解决了问题。 On any JavaScript that I need to send the form I just put:在我需要发送我刚刚输入的表单的任何 JavaScript 上:

document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there

And that skips validation when I do not need it.当我不需要它时,它会跳过验证。 It just sends the form and loads a different page, etc.它只是发送表单并加载不同的页面等。

But if the user clicks the submit button (aka type="button" not type="submit" ) the validation is done before letting the form be submitted and if not valid not sent.但是,如果用户单击提交按钮(又名type="button"而不是type="submit" ),则在提交表单之前完成验证,如果无效则不发送。

Well hope this helps others not to try long and complicated code.希望这可以帮助其他人不要尝试冗长而复杂的代码。 Just not use onsubmit if not needed, and use onclick .如果不需要,请不要使用onsubmit ,并使用onclick But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.但请记住将type="submit"更改为type="button"并且请不要忘记通过 JavaScript 执行submit()

I agree with Shog9, though I might instead use:我同意 Shog9,但我可能会改用:

<input type = "button" onClick="addItem(); return false;" value="Add Item" />

According to w3schools , the <button> tag has different behavior on different browsers.根据 w3schools<button>标签在不同的浏览器上有不同的行为。

You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:您可以使用 jQuery 简单地获取按钮的引用,并防止其传播,如下所示:

 $(document).ready(function () {
    $('#BUTTON_ID').click(function(e) {

            e.preventDefault();
            e.stopPropagation();
            e.stopImmediatePropagation();

            return false;
    });});

$("form").submit(function () { return false; }); that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/> Which will only work if this button isn't the only button in this form.这将阻止按钮提交,或者您可以将按钮类型更改为“按钮” <input type="button"/>而不是<input type="submit"/>仅当此按钮不是此表单中的唯一按钮。

Suppose your HTML form has id="form_id"假设你的 HTML 表单有id="form_id"

<form id="form_id">
<!--your HTML code-->
</form>

Add this jQuery snippet to your code to see result,将此 jQuery 片段添加到您的代码中以查看结果,

$("#form_id").submit(function(){
  return false;
});

Buttons like <button>Click to do something</button> are submit buttons. <button>Click to do something</button>类的按钮是提交按钮。

You must add type您必须添加type

This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:这是一个 html5 错误,就像已经说过的那样,您仍然可以将按钮作为提交(如果您想同时涵盖 javascript 和非 javascript 用户)使用它,例如:

     <button type="submit" onclick="return false"> Register </button>

This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.这样,您将取消提交,但仍然执行您在 jquery 或 javascript 函数中所做的任何事情,并为没有 javascript 的用户执行提交。

Just add e.preventDefault();只需添加e.preventDefault(); in your method should prevent your page from submitting forms.在您的方法中应该阻止您的页面提交表单。

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

According to the MDN Web Docs根据MDN 网络文档

The preventDefault () method of the Event interface tells the user agent that if the event is not explicitly processed, its default action should not be taken into account as it would normally be. Event 接口的 preventDefault () 方法告诉用户代理,如果没有显式处理事件,则不应像通常那样考虑其默认操作。 The event continues to propagate as usual, unless one of its listeners calls stopPropagation () or stopImmediatePropagation () , either of which terminates the propagation.事件继续像往常一样传播,除非其中一个侦听器调用stopPropagation ()stopImmediatePropagation () ,其中任何一个都会终止传播。

The return false prevents the default behavior. return false 防止默认行为。 but the return false breaks the bubbling of additional click events.但 return false 打破了额外点击事件的冒泡。 This means if there are any other click bindings after this function gets called, those others do not Consider.这意味着如果在调用此函数后还有任何其他点击绑定,则其他的不考虑。

 <button id="btnSubmit" type="button">PostData</button>
 <Script> $("#btnSubmit").click(function(){
   // do stuff
   return false;
}); </Script>

Or simply you can put like this或者简单地说你可以这样放

 <button type="submit" onclick="return false"> PostData</button>

I am sure that on FF the我确信在 FF

removeItem 

function encounter a JavaScript error, this not happend on IE函数遇到 JavaScript 错误,这在 IE 上没有发生

When javascript error appear the "return false" code won't run, making the page to postback当出现 javascript 错误时,“return false”代码将无法运行,从而使页面回发

Set your button in normal way and use event.preventDefault like..以正常方式设置按钮并使用 event.preventDefault like..

   <button onclick="myFunc(e)"> Remove </button>  
   ...
   ...

   In function...

   function myFunc(e){
       e.preventDefault();
   }
return false;

You can return false at the end of the function or after the function call.您可以在函数结束时或函数调用后返回 false。

Just as long as it's the last thing that happens, the form will not submit.只要它是最后发生的事情,表单就不会提交。

Here's a simple approach:这是一个简单的方法:

$('.mybutton').click(function(){

    /* Perform some button action ... */
    alert("I don't like it when you press my button!");

    /* Then, the most important part ... */
    return false;

});

The following sample code show you how to prevent button click from submitting form.以下示例代码向您展示了如何防止按钮单击提交表单。

You may try my sample code:你可以试试我的示例代码:

 <form autocomplete="off" method="post" action="">
   <p>Title:
     <input type="text" />
   </p>
   <input type="button" onclick="addItem()" value="Add Item">
   <input type="button" onclick="removeItem()" value="Remove Last Item">
   <table>
     <th>Name</th>

     <tr>
       <td>
         <input type="text" id="input1" name="input1" />
       </td>
       <td>
         <input type="hidden" id="input2" name="input2" />
       </td>
     </tr>
   </table>
   <input id="submit" type="submit" name="submit" value="Submit">
 </form>
<script language="javascript">
function addItem() {
return false;
}

function removeItem() {
return false;
}
</script>

if you have <input />如果你有<input />

use it用它

<input type="button"/>

if you have <button>btn</button>如果你有<button>btn</button>

use it用它

<button type="button">btn</button>

我现在无法对此进行测试,但我认为您可以使用 jQuery 的preventDefault方法。

The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form).函数 removeItem 实际上包含一个错误,这使得表单按钮执行它的默认行为(提交表单)。 The javascript error console will usually give a pointer in this case.在这种情况下,javascript 错误控制台通常会给出一个指针。

Check out the function removeItem in the javascript part:查看 javascript 部分中的函数 removeItem :

The line:该行:

rows[rows.length-1].html('');

doesn't work.不起作用。 Try this instead:试试这个:

rows.eq(rows.length-1).html('');

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

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