devmonster
devmonster

Reputation: 1739

preventDefault javascript doesnt prevent url redirect

My html is

<a class="delete" href="/FolderComment/delete/12">delete</a>

and my js is

$("a .delete").click(function(e){

          //e.preventDefault();   --> tried that too
            var href = this.attr("href");
            $.post(
                href, {},
                function(data){
                    alert(data);
                }
            );
            return false;
        });  

but it doesn't work, the page gets redirected.

here is a jsfiddle

Upvotes: 0

Views: 407

Answers (2)

Alnitak
Alnitak

Reputation: 339816

Your selector should be a.delete - note the lack of space.

As written your callback handler isn't even being invoked because your selector is looking for an element of class .delete that's descended from an <a>, not an <a> that has that class.

Secondly, for security reasons your browser may not permit links to be hijacked if they're going to a remote resource.

As @NickW has pointed out, a page-local link (starting with #) can be redirected. However, if you want your page to work correctly without JS then you may not be able to do that.

A simple fix in that case would be to use JS to rewrite all such links as the page is loaded:

$('a[href^="/"]').attr('href', function(index, val) {
    return '#' + val;
});

Upvotes: 3

nick_w
nick_w

Reputation: 14938

If your href is prepended with #, you should be able to avoid redirection. I have forked your JS fiddle and added in the selector change from @Alnitak.

Upvotes: 1

Related Questions