开发者

How to override (disable) the "submit" behaviour of a button tag inside of a form tag?

开发者 https://www.devze.com 2023-02-12 21:33 出处:网络
<form action=""> <button>click</button> </form> The defaul开发者_如何学编程t behaviour of a button inside a form is to submit that form.
<form action="">
  <button>click</button>
</form>

The defaul开发者_如何学编程t behaviour of a button inside a form is to submit that form.

How can I disable the submit behaviour of that button?


Add a type="button" to it:

<button type="button">Click</button>

The types availabe are:

  • "submit": Default value. Submits the form.
  • "reset": Resets the form's inputs.
  • "button": Does nothing.

A good reference: https://developer.mozilla.org/en/DOM/HTMLButtonElement


This will disable via javascript

<button onclick='return false'>click</button>

But you can just define the type

<button type='button'>click</button>


There are occasions where you want to keep the niceties of a submit button (for instance, on a mobile device, where the submit button can be triggered from the keyboard, but only if the button is part of the form and of type submit). In this case what you need to do is prevent the default action of the button.

Using jQuery 1.7+ (using .on - I highly recommend reading the documentation - there are many nuances to using .on that can vastly affect performance)

$(document).on("click", "button", "event", function(evt) {
    evt.preventDefault();
    ...
}

Using older versions of jQuery...

$("#button-id").bind("click", function(evt, ui) {
    evt.preventDefault();
    ...
}

Note that you can use any selector (select by class, element type etc) or an method of binding to the event (instead of .bind, use .live, .delegate as appropriate to your version of jquery.

0

精彩评论

暂无评论...
验证码 换一张
取 消