Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Click Event PreventDefault

Tags:

javascript

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.

like image 758
Justin Avatar asked Jul 08 '12 00:07

Justin


People also ask

What is event preventDefault () in jQuery?

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.

How do you stop a click event?

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.

What is the use of event preventDefault () method?

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.

How do I disable default without event?

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.


1 Answers

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.

like image 156
sachleen Avatar answered Sep 20 '22 13:09

sachleen