Gasp0de Gasp0de - 10 days ago 7
jQuery Question

jQuery - page refreshing after click

I wrote the following jQuery method, to do something when i click the button with the id 'add':

$(function () {
$('#add').on('click', function () {
$('#headline').text("Hurra!");
});
})


When i add a breakpoint in chromium, i can see that it enters the method, changes the content of the headline, and then changes it back to its original state for some reason (that happens while the debugger is in the minified jquery script, so i don't really know what's happening). Can anyone give me a hint on what might be going on?

Answer

the page is refreshing because the form is getting submitted.

if you dont want it to submit, use return false; or event.preventDefault();

$(function () {
  $('#add').on('click', function(event) {
    $('#headline').text("Hurra!");
    event.preventDefault();
  });
})