Reputation: 389
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
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>
Upvotes: 1
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
Reputation: 631
You can get attribute value of span using attr() function in jQuery
checkBoxValue = $(checkBoxId).attr(checkBoxData);
Upvotes: 1
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 );
} );
});
Upvotes: 0