Manohar Gunturu
Manohar Gunturu

Reputation: 696

event.preventDefault() not working

I had button which had onclick function

<div id="canvas">   
  <button onclick="document.location.href='hello.php'">Go</button>
</div>  

Now I want to stop this onclick event which redirects to hello.php, so I have written the following jQuery function

$("#canvas").on('click', 'button', function(event) {
  event.preventDefault();
});

This didn't work so I added a return false but it's still not working.

$("#canvas").on('click', 'button', function(event) {
  event.preventDefault();
  return false;
});

You can view it at Jsfiddle

Note: I do not want to remove onclick of button

Upvotes: 1

Views: 1357

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074038

The correct solution is to remove the onclick from the HTML in the first place.

Assuming that's not possible, you can remove it after the fact:

$("#canvas button").first().prop("onclick", null);

That clears the onclick property on the element, which removes the handler set up by the onclick attribute. (It's a no-op if the button doesn't exist at all.)

It's probably worth noting that if the button is in a form, it will now submit the form, since its onclick isn't taking the user away from the page. (Since button's default type is submit.)

Upvotes: 6

Rob M.
Rob M.

Reputation: 36511

You should just use the removeAttr jQuery method:

$('#canvas button').removeAttr('onclick');

Upvotes: 2

Related Questions