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>
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.
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
type="button" is the answer as you said.
<button type="button" class="btn btn-info" id="calculate" onclick="calculate()"> Calculate </button>