Wasbeer
Wasbeer

Reputation: 389

Retrieving jQuery data from dynamic HTML element returns undefined

I am trying to retrieve data from a variable HTML element. On click, the id of the <span> element is retrieved, which I want to enable me to dynamically $([dynamic id]) select that element and request the data stored in the data attribute.

My jQuery looks like this:

$( document ).ready( function() {
    $( ".checkmark" ).on( "click", ( event ) => {
        let checkBoxId = "#" + event.target.id, // #checkBox1
            checkBoxData = event.target.id + "-value", // checkBox1-value
            checkBoxValue = $( checkBoxId ).data( checkBoxData ); // undefined
    } );
} );

The HTML element targeted looks like this:

<span class="checkmark" id="checkBox1" data-checkBox1-value=-155></span>

The value of let checkBoxValue is undefined and I cannot figure out why. Help would be greatly appreciated.

Upvotes: 2

Views: 595

Answers (5)

Ikhlak S.
Ikhlak S.

Reputation: 9034

It seems you are having scope issues with the new ()=>{} syntax.

So, you will need to bind this to the function event handler using {self:this}. If you don't want to do this, you can use the old function(){} syntax instead.

$( document ).ready( function() {
    $( ".checkmark" ).on( "click", {self:this}, ( event ) => {
        var checkBoxValue = $(this).data("checkbox1-value")
        alert(checkBoxValue);
    } );
} );

And also as @Erwin mentioned, use only lowercase in your data- attribute name:

<span class="checkmark" id="checkbox1" data-checkbox1-value="-155"></span>

JsFiddle

Upvotes: 1

user557419
user557419

Reputation:

The checkBoxId variable is unnecessary because you can use the this keyword since it is the current element you are working with.

$(function() {
    $(".checkmark").on("click", (event) => {
        let checkBoxData = event.target.id + "-value";
        let checkBoxValue = $(this).data(checkBoxData);
    });
});

Upvotes: 1

agit
agit

Reputation: 631

You can get attribute value of span using attr() function in jQuery

checkBoxValue = $(checkBoxId).attr(checkBoxData);

Upvotes: 1

Mahmoud Nabil
Mahmoud Nabil

Reputation: 21

this code works for me try it ;)

$( document ).ready( function() {
    $( ".checkmark" ).on( "click",  function()  {
        var checkBoxId = "#" + $(this).attr('id');
          var  checkBoxData =  $(this).attr('id') + "-value";
        $( this ).attr('data-'+ checkBoxData, 155 );
    } );
});

jsfiddle link

Upvotes: 0

Goma
Goma

Reputation: 1981

It's returning undefined because it is declared incorrectly. The part after data- should be in lower case. In your case, it must be

<span class="checkmark" id="checkbox1" data-checkbox1-value=-155></span>

for the .data() to work.

Upvotes: 0

Related Questions