Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clicking a button within a form causes page refresh

People also ask

How do I stop my page from refreshing on button click?

you have to specify the parameters, if you simple use window. location = window. location. href; it'll refresh the whole page & it'll resets all your previous requests.

Why does my button refresh the page?

Your page is reloading because the button is submitting your form. The submit will, by default, re-load the page to show form errors or the result of the submit action. The cleanest fix is, as you discovered, to specify a button type.

How do I refresh a page that clicks a button?

reload() method or the window. reload() method gives the same result as pressing the reload button on your browser. This method reloads the page from directly the browser's cache by default. If the forceGet property is set to true, the web page will be reloaded from the server.

How do I stop a form from refreshing the page?

Use the preventDefault() method on the event object to prevent a page refresh on form submit in React, e.g. event. preventDefault() . The preventDefault method prevents the browser from issuing the default action which in the case of a form submission is to refresh the page.


If you have a look at the W3C specification, it would seem like the obvious thing to try is to mark your button elements with type='button' when you don't want them to submit.

The thing to note in particular is where it says

A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit"


You can try to prevent default handler:

html:

<button ng-click="saveUser($event)">

js:

$scope.saveUser = function (event) {
  event.preventDefault();
  // your code
}

You should declare the attribute ng-submit={expression} in your <form> tag.

From the ngSubmit docs http://docs.angularjs.org/api/ng.directive:ngSubmit

Enables binding angular expressions to onsubmit events.

Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page).


I use directive to prevent default behaviour:

module.directive('preventDefault', function() {
    return function(scope, element, attrs) {
        angular.element(element).bind('click', function(event) {
            event.preventDefault();
            event.stopPropagation();
        });
    }
});

And then, in html:

<button class="secondaryButton" prevent-default>Secondary action</button>

This directive can also be used with <a> and all other tags


You can keep <button type="submit">, but must remove the attribute action="" of <form>.