How to prevent buttons from submitting forms

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

    You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:

     $(document).ready(function () {
        $('#BUTTON_ID').click(function(e) {
    
                e.preventDefault();
                e.stopPropagation();
                e.stopImmediatePropagation();
    
                return false;
        });});
    
    0 讨论(0)
  • 2020-11-21 05:32

    The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. 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>
    
    0 讨论(0)
  • 2020-11-21 05:33

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

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

    I agree with Shog9, though I might instead use:

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

    According to w3schools, the <button> tag has different behavior on different browsers.

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

    The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.

    Check out the function removeItem in the javascript part:

    The line:

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

    doesn't work. Try this instead:

    rows.eq(rows.length-1).html('');
    
    0 讨论(0)
提交回复
热议问题