Can I make a <button> not submit a form?

前端 未结 8 1092
耶瑟儿~
耶瑟儿~ 2020-11-22 05:36

I\'ve got a form, with 2 buttons



相关标签:
8条回答
  • 2020-11-22 05:45
    <form onsubmit="return false;">
       ...
    </form>
    
    0 讨论(0)
  • 2020-11-22 05:47

    Honestly, I like the other answers. Easy and no need to get into JS. But I noticed that you were asking about jQuery. So for the sake of completeness, in jQuery if you return false with the .click() handler, it will negate the default action of the widget.

    See here for an example (and more goodies, too). Here's the documentation, too.

    in a nutshell, with your sample code, do this:

    <script type="text/javascript">
        $('button[type!=submit]').click(function(){
            // code to cancel changes
            return false;
        });
    </script>
    
    <a href="index.html"><button>Cancel changes</button></a>
    <button type="submit">Submit</button>
    

    As an added benefit, with this, you can get rid of the anchor tag and just use the button.

    0 讨论(0)
  • 2020-11-22 05:47

    Yes, you can make a button not submit a form by adding an attribute of type of value button: <button type="button"><button>

    0 讨论(0)
  • 2020-11-22 06:01

    The default value for the type attribute of button elements is "submit". Set it to type="button" to produce a button that doesn't submit the form.

    <button type="button">Submit</button>
    

    In the words of the HTML Standard: "Does nothing."

    0 讨论(0)
  • 2020-11-22 06:01

    Just use good old HTML:

    <input type="button" value="Submit" />
    

    Wrap it as the subject of a link, if you so desire:

    <a href="http://somewhere.com"><input type="button" value="Submit" /></a>
    

    Or if you decide you want javascript to provide some other functionality:

    <input type="button" value="Cancel" onclick="javascript: someFunctionThatCouldIncludeRedirect();"/>
    
    0 讨论(0)
  • 2020-11-22 06:04

    The button element has a default type of submit.

    You can make it do nothing by setting a type of button:

    <button type="button">Cancel changes</button>
    
    0 讨论(0)
提交回复
热议问题