tags:

views:

209

answers:

3

Hi there,

I'm creating a little dynamic tooltip function.

Basically if I have a link like so:

<a href="#" data="xyz">?</a>

Using qTip, I attempt to lookup a tooltip table in mysql and retrieve the tip based on the data in the data attribute.

So:

$('a[data]').qtip({ 
    content: {
       url: '/tooltip.php',
       data: { tipKey: $(this).attr('data') },
       method: 'post'
}
});

Problem is, it doesn't work. $(this).attr('data') doesn't seem to pull the value inside the attribute.

If I manually change the function so it looks like the following it works no problem.

    $('a[data]').qtip({ 
 content: {
  url: '/tooltip.php',
  data: { tipKey: 'xyz' },
  method: 'post'
 }

});

What am I missing when I'm trying to pull the data from the data attribute? Should I be doing something like:

    $('a[data]').qtip({ 
 content: {
  url: '/tooltip.php',
  data: { tipKey: ''+$(this).attr('data')+'' },
  method: 'post'
 }

});

As that isn't yielding the value either!

+1  A: 

This example works for me:

<html>
<head>
<title>Text</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
<script type="text/javascript">
$(function() {
  alert($("a[data]").text());
});
</script>
</head>
<body>
<a href="#" data="123">abc</a>
</body>
</html>
cletus
Well he's looking for getting the attribute, not the text of the link right?
AlbertoPL
Correct Alberto... the attr not the stuff inbetween the <a></a>
cosmicbdog
+1  A: 

You should try accessing the 0th element of data. Like this:

data: { tipKey: $("a[data]")[0].data},

EDIT: oh ok, i see, this should work then as an alternative.

AlbertoPL
hmmm... i hoped it would work but it did not :|
cosmicbdog
+2  A: 

Your code doesn't works because the this keyword represents the context of the function that is being executed, and you are using it inside an object literal.

For example, if you execute your snippet in the $(document).ready event, the this keyword will represent the document element.

You could iterate over your selector and initialize each element tooltip individually:

$('a[data]').each(function () {
  var $link = $(this);
  $link.qtip({ 
      content: {
        url: '/tooltip.php',
        data: { tipKey: $link.attr('data') },
        method: 'post'
      }
  });
});

Also note that the data attribute is not standard, your page will not pass the W3C Validator.

CMS
thanks heaps CMS... i've shifted from 'data' to 'title' and your solution worked a treat.
cosmicbdog