-1

i have to use a span custom attribute for multiple reasons. Here i can use the attribute first time when clicking a <a>. But second time it is undefined in alert. Here is html

<span data="<?php echo $key; ?>"><?php echo $answer['vote']; ?></span>
<a href="#" class="tup" rel="<?php echo $answer['id']; ?>"><span class="glyphicon glyphicon-thumbs-up design-thumbs" id="thumbs-up-ico"></span></a>
<a href="#" class="tdown" rel="<?php echo $answer['id']; ?>"><span class="glyphicon glyphicon-thumbs-down" id="thumbs-down-icon"></span></a>

Jquery

$(document).ready(function() {                       
$( ".tup" ).click(function(event) {
    event.preventDefault();
    var id = this.rel;
    var key = $(this).prev().attr('data');
    alert(key) ////////it's ok
});

$( ".tdown" ).click(function(event) {
    event.preventDefault();
    var id = this.rel;
    var key = $(this).prev().attr('data');
    alert(key);///////Undefined
});

});

how can i solve the problem?thanks

EDIT i gave id to it. But my id is given with an array in php. So i had to use another attribute to identify the id

<span id="<?php echo $key; ?>" data-key="<?php echo $key; ?>"><?php echo $answer['vote']; ?></span>
8
  • 1
    I don't see any .tdown in you html
    – user180100
    Feb 5, 2014 at 11:29
  • data atrribute should be data-* attribute, e.g data-key="<?php echo $key; ?>" then use instead: $(this).prev().data('key');
    – A. Wolff
    Feb 5, 2014 at 11:29
  • Show the entire markup please. Feb 5, 2014 at 11:30
  • now edited.added another <a>
    – andDev
    Feb 5, 2014 at 11:32
  • @AlessandroMinoccheri already given you example at your qusetion get custom attribute value in jquery. On how to use a custom attribute in jquery
    – Satpal
    Feb 5, 2014 at 11:33

1 Answer 1

1

Your code would work only if link is next to either <span class="tup"> or <span class="tdown">. In any other case it won't work.

You're most likely want to use the following selector to find your span:

$(this).prevAll('span[data]').last().attr('data');
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.