How to prevent buttons from submitting forms

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

    Suppose your HTML form has id="form_id"

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

    Add this jQuery snippet to your code to see result,

    $("#form_id").submit(function(){
      return false;
    });
    
    0 讨论(0)
  • 2020-11-21 05:16
    return false;
    

    You can return false at the end of the function or after the function call.

    Just as long as it's the last thing that happens, the form will not submit.

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

    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>
    
    0 讨论(0)
  • 2020-11-21 05:20

    Set your button in normal way and use event.preventDefault like..

       <button onclick="myFunc(e)"> Remove </button>  
       ...
       ...
    
       In function...
    
       function myFunc(e){
           e.preventDefault();
       }
    
    0 讨论(0)
  • 2020-11-21 05:21

    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;
    
    });
    
    0 讨论(0)
  • 2020-11-21 05:22

    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:

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

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