How to prevent buttons from submitting forms

后端 未结 17 2055
礼貌的吻别
礼貌的吻别 2020-11-21 04:43

In the following page, with Firefox the remove button submits the form, but the add button does not.

How do I prevent the remove button from submitting t

相关标签:
17条回答
  • 2020-11-21 05:22

    I am sure that on FF the

    removeItem 
    

    function encounter a JavaScript error, this not happend on IE

    When javascript error appear the "return false" code won't run, making the page to postback

    0 讨论(0)
  • 2020-11-21 05:24

    I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.

    0 讨论(0)
  • 2020-11-21 05:25

    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:

    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.

    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:

    $(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.

    0 讨论(0)
  • 2020-11-21 05:28

    You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here: W3C HTML5 Button

    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.

    0 讨论(0)
  • 2020-11-21 05:29

    Just add e.preventDefault(); in your method should prevent your page from submitting forms.

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

    According to the MDN Web Docs

    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. The event continues to propagate as usual, unless one of its listeners calls stopPropagation () or stopImmediatePropagation (), either of which terminates the propagation.

    0 讨论(0)
  • 2020-11-21 05:30

    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).

    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. 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).

    The problem is that the form is always submitted, no matter if onclick returns true or false.

    If I change type="submit" for type="button", it seems to work but does not. 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; is, I also add a JavaScript submit sentence, something similar to this:

    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.

    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.

    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.

    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.

    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!

    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.

    If I do the work on onsubmit on the form tag, I would need to know if it is the user or other 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. Insead put it where it really is needed, on the button.

    For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. 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)

    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. 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:

    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.

    Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.

    0 讨论(0)
提交回复
热议问题