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

isherwood
  • 58,414
  • 16
  • 114
  • 157
MacMan
  • 925
  • 1
  • 14
  • 32

1 Answers1

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"
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    The comment on `val()` is really the key here. There's nothing wrong with using `attr()` unless the data are being updated dynamically. See http://stackoverflow.com/questions/7261619/jquery-data-vs-attr. – isherwood Jan 26 '15 at 14:32
  • Perfect thanks - I hadn't realised about the `data` attribute, but I will remember that.. Thanks again – MacMan Jan 26 '15 at 17:03