I'm having trouble using the event.preventDefault();
for an ahref
on my DOM.
How do you prevent the url from posting a nofollow delete, as specified by the HTML using JQuery?
<td class="trash_can">
<a rel="nofollow" data-remote="true" data-method="delete" data-confirm="Are you sure you want to delete Greek Theater at U.C. Berkeley?" href="/promotions/2/places/46">
<img id="trash_can" src="http://test.dev/images/trash.png?1305741883" alt="Trash">
The following code should subvert the HTML but the HTML posts a delete action, prior to giving a "are you sure" warning. nothing is not working:
$(function(){
$('.trash_can a').click(function(event) {
event.preventDefault();
console.log('Clicked Delete');
});
});
Nowadays, you should usually use native HTML form validation instead.
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.
stopPropagation() event method: This method is used to prevent the parent element from accessing the event. Basically, this method is used to prevent the propagation of the same event from being called.
stopPropagation prevents further propagation of the current event in the capturing and bubbling phases. preventDefault prevents the default action the browser makes on that event.
It is possible that instead of just event.preventDefault()
, you need to do return false
also or instead. preventDefault() prevents the default action, but the event still bubbles up, possibly to the next handler, which could be the rails handler that Fredrik pointed out:
$(rails.linkClickSelector).live('click.rails', function(e) {
var link = $(this);
if (!rails.allowAction(link)) return rails.stopEverything(e);
if (link.data('remote') !== undefined) {
rails.handleRemote(link);
return false;
} else if (link.data('method')) {
rails.handleMethod(link);
return false;
}
});
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