Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop page reload on button click jquery

I am using this below code for button click event using jQuery. When button is clicked the page reloads.

$('#button1').click(function () {
    //Code goes here
    return false;
});
like image 386
Vicky Avatar asked Nov 01 '15 18:11

Vicky


People also ask

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

To do not refresh the page we add event. preventDefault(); at the end of our JavaScript function.

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 stop my html page from refreshing?

Use jQuery's submit event to handle the form submit, add return false; at the end of the submit handle function to prevent the page to reload. return false ; }); });


2 Answers

You can use event.preventDefault() to prevent the default event (click) from occurring.

$('#button1').click(function(e) {
    // prevent click action
    e.preventDefault();
    // your code here
    return false;
});
like image 73
doublesharp Avatar answered Oct 16 '22 07:10

doublesharp


If your "button" is a button element, make sure you explicity set the type attribute, otherwise the WebForm will treat it as submit by default.

<button id="button1" type="button">Go</button>

If it's an input element, do so with jQuery with the following:

$('#button1').click(function(e){
    e.preventDefault();
    // Code goes here
});

Read more: event.preventDefault()

like image 31
Goran Mottram Avatar answered Oct 16 '22 08:10

Goran Mottram