Search code examples
javascripthtmlconfirm

How can I get the href value of clicked element?


Here is my code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.rawgit.com/makeusabrew/bootbox/master/bootbox.js"></script>

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<a onclick="return bootbox.confirm('are you sure?', function(e){ if (e) {window.location = this.href;} });" href="/Remove-Post/{{ $tb }}/{{$post->id}}" data-toggle="modal" data-target="#confirm-delete">Link</a>

Noted that I use this library for confirm.

But this line doesn't work in my code:

window.location = this.href;

And it always (when I click OK) redirects me here:

http://localhost:8000/undefined

How can I fix it?


Solution

  • <a onclick="return bootbox.confirm('are you sure?', function(e){ if (e) {window.location.href = $(this).attr('href');} });" href="/Remove-Post/{{ $tb }}/{{$post->id}}" data-toggle="modal" data-target="#confirm-delete">
    

    Instead of onClick you can do something like this.

    <a id="some-id" href="/Remove-Post/{{ $tb }}/{{$post->id}}" data-toggle="modal" data-target="#confirm-delete">
    $('#some-id').click(function(){
        var link = $(this).attr('href');
        bootbox.confirm('are you sure ?', function(e){
          if(e){
             window.location.href = link;
           }
        })
    })