How to prevent buttons from submitting forms

后端 未结 17 2062
礼貌的吻别
礼貌的吻别 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:25

    Set the type on your buttons:

    
    
    

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

    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.

提交回复
热议问题