MacMan
MacMan

Reputation: 933

Getting specific attribute value

I have a a href which is formatted as :

<a href class='link' location='USA'>USA</a>

I'm then using JQuery to try and get the value of location and pass that to a new page.

$(".link").click( function() {
   var location = $(this).attr("location").val();
   Popup('open.php?action=region&location=' + location,'open','300','200','yes');return false;
});

This isn't working.

I'm not getting the value of location passed.

Can someone advise what I've done wrong !

Thanks

Upvotes: 1

Views: 33

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337560

Firstly inventing attributes which don't conform to the standard will mean your HTML is invalid which could lead to both UI and JS issues. Use data attributes to store custom data in an element:

<a href="#" class='link' data-location='USA'>USA</a>

You can then access this in your click handler using data():

$(".link").click(function(e) {
    e.preventDefault(); // stop the default link behaviour
    var location = $(this).data("location");
    Popup('open.php?action=region&location=' + location, 'open', '300', '200', 'yes');
    return false;
});

Just for your reference, when accessing an attribute of an element via attr() you don't need to call val() on it, for example:

var foo = $("#element").attr("foo"); 
console.log(foo); // = "bar"

Upvotes: 3

Related Questions