0

i have two span's and where i have a custom attribute. I want to get the value of it by clicking <a>.Here is my 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>

Jquery

$(document).ready(function() {                       
$( ".tup" ).click(function(event) {
    event.preventDefault();
    var key = $('span').attr('data');
    alert(key);
});

Here i get undefined in alert.Where is my error?Thanks

3 Answers 3

5

You are most likley getting undefined because you are not selecting the wanted span, use .prev() to select it

$( ".tup" ).click(function(event) {
    event.preventDefault();
    var key = $(this).prev().attr('data');
    //               ^^^^^^^^
    alert(key);
});
Sign up to request clarification or add additional context in comments.

1 Comment

@andDev since this is the correct answer, then click the grey tick to make it green :)
3

you need to use data-key(or another value, data-id, data-attr....) and retrieve it in jQuery with .data(key)
You need to get the previous element with prev() try this:
HTML

<span data-key="<?php echo $key; ?>"><?php echo $answer['vote']; ?></span>

jQuery

$(document).ready(function() {                       
$( ".tup" ).click(function(event) {
    event.preventDefault();
    var key = $('span').prev().data('key');
    alert(key);
});

Comments

0

Storing data in this way is not valid. You can use html5 data-* propery for custom attribute, for example:

<!DOCTYPE html>
...
<span data-key="some data">value</span>
<script>
var key = $("span").data("key");
</script>

Comments

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.