If I have an a
tag:
<a id="delete-event" href="/delete/1234">Delete</a>
And some javascript which prompts to confirm the delete:
$("#delete-event").click(function(e) {
e.preventDefault();
bootbox.confirm("Are you sure you wish to delete this?", function(confirmed) {
if(confirmed) {
return true;
}
});
});
I thought doing e.preventDefault()
would prevent the a href
from firing, but its not. When I click the a tag it simply goes to the url, without executing the javascript. How can I make this work?
Thanks.
The event. preventDefault() method stops the default action of an element from happening. For example: Prevent a submit button from submitting a form. Prevent a link from following the URL.
To stop an event from further propagation in the capturing and bubbling phases, you call the Event. stopPropation() method in the event handler. Note that the event. stopPropagation() method doesn't stop any default behaviors of the element e.g., link click, checkbox checked.
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
preventDefault() This method stops the event if it is stopable, meaning that the default action that belongs to the event will not occur. It just prevent the default browser behaviour. Developers use preventDefault() in many cases For example, When clicking on a link, prevent the link from following the URL.
This code works:
You can't just do return true
and expect the link to fire after you've done e.preventDefault()
. I had to replace your bootbox.confirm()
with a JS confirm but it should still work.
$("#delete-event").click(function(e) {
e.preventDefault();
var a = confirm("yes?");
if(a) window.location = $('#delete-event').attr('href');
});
DEMO
Try replacing your code block with the one I provided above. If that works, put your bootbox
confirmation back in and try again. That'll tell you where the error is.
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