Shermaine Chaingan
Shermaine Chaingan

Reputation: 242

Why does 'return false' not prevent page reload on onclick

I already tried this code but it does not prevent page reload on onclick function. What should I do? Did I miss something or is this a browser compatibility issue?

function track_specs() {
  $('button[name="delete_spec"]').each(function() { 
    this.onclick = null; 
    $(this).click(function () { 
      delete_specs($(this).data("id")); 
      return false; 
    }); 
  });
}

Upvotes: 3

Views: 2060

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Instead of the code, can you try this? You don't need to loop through all the <button> tags which is a costly one. You can use this:

$(document).ready(function () {
  $('button[name="delete_spec"]').click(function (e) {
    e.preventDefault();
    delete_specs($(this).data("id")); 
  });
});

Upvotes: 3

Will
Will

Reputation: 20235

A <button> shouldn't initiate a page reload on click unless you have another click listener that reloads the page or maybe in your delete_specs function.

You could try this:

$(this).click(function(e) {
  e.preventDefault();
  ...
});

But I think you are explicitly reloading the page somewhere else (through window.location = ...).

Upvotes: 1

Related Questions