1

I have a form on my page and a button with id "calculate" in the form. When I press the button it will do some calculations using a function. But when I press the button it behaves like a submit button and sends the data. I don't want to send the form, I just want to calculate.

<form method="post" action="" enctype="multipart/form-data" id="form_add_data">
...
<button class="btn btn-info" id="calculate" onclick="calculate()"> Calculate </button>
...
</form>
RobC
  • 22,977
  • 20
  • 73
  • 80
Caravansary
  • 73
  • 1
  • 1
  • 9
  • 1
    noob mistake, any click on a form button defaults to submit. you must specify the `type` of your button https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Button#attr-type – Mister Jojo Aug 24 '21 at 00:36

3 Answers3

2

Inside calculate function use:

function calculate(event){
    event.preventDefault()
    return false;
}

Prevent default will stop event propagation, and return false will keep the page from being refreshed.

Pelicer
  • 1,348
  • 4
  • 23
  • 54
1

You should use Event.preventDefault().

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.

In your situation:

document.getElementById("calculate").addEventListener("click", function(event){
  event.preventDefault()
});

or:

// in your JS file
function calculate(event){
      event.preventDefault()
}

read more about it here on MDN

Haitham6373
  • 1,139
  • 8
  • 10
0

type="button" is the answer as you said.

<button type="button" class="btn btn-info" id="calculate" onclick="calculate()"> Calculate </button>
Caravansary
  • 73
  • 1
  • 1
  • 9