I have a link on a web page. When a user clicks it, a widget on the page should update. However, I am doing something, because the default functionality (navigating to a different page) occurs before the event fires.
This is what the link looks like:
<a href="store/cart/" class="update-cart">Update Cart</a>
This is what the jQuery looks like:
$('.update-cart').click(function(e) { e.stopPropagation(); updateCartWidget(); });
What is the problem?
The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form.
The preventDefault() Method in jQuery is used to stop the default action of selected element to occur. It is also used to check whether preventDefault() method is called for the selected element or not. Syntax: event.preventDefault()
Kavitha, try this one. Create a hidden field named clicked and initialize its value to 0. for the first time if you click make the value in the hidden filed as 1. The next time you click check the value of hidden filed, if it is 1 then it is already clicked.
e.preventDefault();
from https://developer.mozilla.org/en-US/docs/Web/API/event.preventDefault
Cancels the event if it is cancelable, without stopping further propagation of the event.
$('.update-cart').click(function(e) { updateCartWidget(); e.stopPropagation(); e.preventDefault(); }); $('.update-cart').click(function() { updateCartWidget(); return false; });
The following methods achieve the exact same thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With