Can I make a

Can I make a

I’ve got a form, with 2 buttons

I use jQuery UI’s button on them too, simply like this
$(‘button’).button();

However, the first button also submits the form. I would have thought that if it didn’t have the type=”submit”, it wouldn’t.
Obviously I could do this
$(‘button[type!=submit]’).click(function(event) { event.stopPropagation(); });

But is there a way I can stop that back button from submitting the form without JavaScript intervention?
To be honest, I used a button only so I could style it with jQuery UI. I tried calling button() on the link and it didn’t work as expected (looked quite ugly!).

Solutions/Answers:

Solution 1:

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

Solution 2:

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>

Solution 3:

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();"/>

Solution 4:

<form onsubmit="return false;">
   ...
</form>

Solution 5:

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.

Solution 6:

Without setting the type attribute, you could also return false from your OnClick handler, and declare the onclick attribute as onclick="return onBtnClick(event)".