I am failing to save some values (that I get through a for loop) into an HTML button as the buttons data- attributes.
In the following for loop code, you will notice how I indicate that the values are successfully captured by console login them out.
Why am I failing to save them in the buttons data-attributes can someone point out where I am going wrong?
Find below the code to my for loop and its successful console log results:
contractMethods.viewAllGifts().call( (error, result)=> {
if(!error){
result.forEach((item, index)=>{
console.log("item.tokenId: " item.tokenId);
console.log("item.messageToRecipient: " item.messageToRecipient);
$('#assetInheritor').append('<button type="button" value=' item.tokenId ' ' 'data-value1=' item.messageToRecipient ' ' ' onclick="fetchValue(this)"> ' item.tokenId '</button> ');
})
}
})
The console in the code above, successfully logs out:
item.tokenId: 100
item.messageToRecipient: I love you Mamma!
Find below the code to the onclick="fetchValue() and its errornous results:
function fetchValue(_button){
console.log(_button.value);
console.log(_button.dataset.value1)
}
The first console logs out: 100, instead of: 100
while the second one console logs out: I instead of: I love you Mamma!
Can someone kindly point out where I am going wrong?
Thanks the second
CodePudding user response:
I see your problem is that you are appending a button each time for a single. Instead of setting a button like that use attr to set an attribute after the button was appended:
// Dummy data
const result = [
{
tokenId: 100,
messageToRecipient: "Message 1",
},
{
tokenId: 101,
messageToRecipient: "Message 2",
}
]
// updated forEach
result.forEach((item, index)=>{
$('#assetInheritor').append(`<button id="button-${index}" onclick="fetchValue(this)">Button ${index 1}</button> <br/> <br/>`);
$(`#button-${index}`).attr("data-value1", item.tokenId);
$(`#button-${index}`).attr("data-value2", item.messageToRecipient);
})
// updated function
function fetchValue(_button){
console.log(_button.dataset.value1);
console.log(_button.dataset.value2)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="assetInheritor"></div>
