Disable form auto submit on button click

Disable form auto submit on button click

I have a HTML form where I use several buttons. The problem is that no matter which button I click, the form will get submitted even if the button is not of type “submit”. e.g. Buttons like :, result in form submission.
It’s quite painful to do an e.preventDefault() for each one of these buttons.
I use jQuery and jQuery UI and the website is in HTML5.
Is there a way to disable this automatic behavior?

Solutions/Answers:

Solution 1:

Buttons like <button>Click to do something</button> are submit buttons.

Set type="button" to change that. type="submit" is the default (as specified by the HTML recommendation).

Solution 2:

It is not hard to do what you want.
You could just try using return false (return false overrides default behaviour on every DOM element) like that :

myform.onsubmit=function()
{ 
  //do what you want;
  return false;
}

and then submit your form using myform.submit()

Related:  How to get Twitter Bootstrap Modal's invoker element?

or alternatively :

mybutton.onclick=function () 
{
   //do what you want;
   return false;
}

However I think Input type=”button”/Button type=”button” will not submit your form and you could use them without any problems.

Solution 3:

<button>‘s are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!

$('form button').on("click",function(e){
    e.preventDefault();
});

Solution 4:

if you want to add directly to input as attribute, use this

 onclick="return false;" 

<input id = "btnPlay" type="button" onclick="return false;" value="play" /> 

this will prevent form submit behaviour