soiswis
soiswis

Reputation: 71

How do I get anchor href value on click using jQuery?

Let's say I have an anchor like this:

<a onClick="return confirm('Sure?')" href="http://stackoverflow.com/">Click here</a>

Is there anyway I can get the value of href "http://stackoverflow.com/" when I click "Click here"? Bearing in mind that I don't have other attributes to help, such as id or name!

I'm overriding the confirm function and I need to redirect the user to the location provided in the anchor if they clicked ok as follows:

window.confirm = function(msg) {
      var targetUrl = jQuery(this).attr("href");
      jQuery("#alert_box").dialog({
         autoOpen: false,
         show: "slide",
         modal: true,
         width: 400,
         resizable:false,
         title: '<img src="icons/confirm.png" /> Confirm!',
         buttons: { "Cancel": function() { 
                        jQuery(this).dialog("close");                       
                    },
                 "OK": function() { 
                        //jQuery(this).dialog("close");
                        jQuery(location).attr('href', targetUrl);
                    }
                   }
      });

      jQuery("#alert_box").html(msg);
      jQuery("#alert_box").dialog("open");
      return false;
  }

Any help would be much appreciated!

Upvotes: 1

Views: 6985

Answers (1)

Konstantin Tarkus
Konstantin Tarkus

Reputation: 38368

To redirect a user use:

window.location.href = targetUrl;

instead of:

jQuery(location).attr('href', targetUrl);

Also it is a good idea remove inline JavaScript, for example:

<a class="confirm" href="http://www.example.com">..</a>

// script.js
$('a.confirm').click(function(e) {
    e.preventDefault();
    if (confirm('Are you sure?')) {
        window.location.href = $(this).attr('href');
    }
});

Also this inside your confirm function declaration is not referred to the <a> element. You may want to use something like:

<a onclick="return confirm(this, 'Sure?')" href="...">...</a>

// script.js
function confirm(e, msg) {
    var targetUrl = $(e).href('attr');
    // ...
}

Upvotes: 3

Related Questions