Marcatectura
Marcatectura

Reputation: 1695

Accessing a value from a jQuery object created from .data()

I've got several HTML elements with various data-attributes. I'm trying to use jQuery to store all of the data attributes for a particular element when it's clicked, then insert one of the values from that Object into another element as text. I've tried various approaches I've seen on SO, and I think I'm properly storing the data, but I can't figure out a straightforward way to pull out a particular data-attribute value so I can insert it in the #display element. The HTML:

<span class="source" data-spanName="spanOne" data-spanPosition="first">Span One</span>
<span class="source" data-spanName="spanTwo" data-spanPosition="second">Span Two</span>
<span class="source" data-spanName="spanThree" data-spanPosition="third">Span Three</span>

<span id="display">display attribute here</span>

The jQuery I've tried:

Attempt 1 (returns [object Object]):

$('.source').click(function () {
    var rowData = $( this ).data();
    $('#display').text( rowData ); //returns [object Object]
});

Attempt 2 (returns undefined):

$('.source').click(function () {
    var rowData = $( this ).data();
    $('#display').text( $.rowData[0].spanname ); //returns undefined
});

Attempt 3 (displays all data, but as a string):

$('.source').click(function () {
    var rowData = $( this ).data();
    var prettyRowData = JSON.stringify( rowData );
    $('#display').text( prettyRowData ); //returns attributes, but as a string and I'd have to parse it to pull out a value 
});

Desired end result:

<span id="display">spanOne</span>

Upvotes: 0

Views: 69

Answers (3)

Adrian Covaci
Adrian Covaci

Reputation: 103

$('.source').click(function(){
    var text = $(this).data('spanName');
    $('#display').text(text);
});

Upvotes: 0

ncksllvn
ncksllvn

Reputation: 5769

The naming conventions for data attributes are explained pretty well here

But your second attempt seems really close. However, you're accessing an object as if it's an Array, so you'll need to try a different way to access it:

$('.source').click(function () {
    var rowData = $( this ).data();

    // proper way to get the data
    var spanName = rowData.spanname;
    $('#display').text( spanName ); 

});

Upvotes: 3

Cloud_Ratha
Cloud_Ratha

Reputation: 618

Try this:

name = $(this).attr('data-spanName');
pos = $(this).attr('data-spanPosition');

Upvotes: 1

Related Questions