Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm having trouble using the event.preventDefault(); for an ahref on my DOM

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');
  });
});
like image 565
JZ. Avatar asked Jun 09 '11 17:06

JZ.


People also ask

What can I use instead of event preventDefault?

Nowadays, you should usually use native HTML form validation instead.

How do you use event preventDefault?

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.

Which event can be used to stop event propagation in react AE preventDefault () be stopPropagation () C None D all?

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.

What's the difference between event preventDefault () and event stopPropagation ()?

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.


1 Answers

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;
    }
  });
like image 88
slolife Avatar answered Oct 28 '22 19:10

slolife