1

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

0

1 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

2 Comments

The comment on val() is really the key here. There's nothing wrong with using attr() unless the data are being updated dynamically. See stackoverflow.com/questions/7261619/jquery-data-vs-attr.
Perfect thanks - I hadn't realised about the data attribute, but I will remember that.. Thanks again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.