I have searched for possible solutions online but did not find any solutions that actually work.I have tried multiple approaches but sadly none of them work according to the way that I need it work in this specific regard. I saw that I could use the href and button approach using the router but this is sadly not the specific solution required in this instance.
Basically I need to get the id value of a specific object displayed in a html list when a button is clicked on the browser. Say a list displays 2 json objects in html then when button 2 in the list is clicked I want to retrieve the id of that second element in the list to display later in another list or save it later in a database or whatever is clever.
The code of the list and array of objects is added here but code so far of how I tried to solve this is not listed because none of my attempts even worked and each attempt failed dismally(a bit over reacting but hey) :=(
So basically I need help and advice :=)
var details = [
{
id: 0,
department: "HR",
name: "samy",
},
{
id: 1,
department: "Accounting",
name: "william",
}
];
function displaydetails(parent, array) {
var html = "";
for (i = 0; i < array.length; ++i) {
//Set Our Itemp template
let itemTemplate = `
<li>
<h2>${array[i].department}</h2>
<div>name: ${array[i].name}</div>
<div>id: ${array[i].id}</div>
<div> <button id='retrieve-ID' > GET ID </button> </div>
</li>`;
//update the html
html += itemTemplate
}
//Update the parent once
parent.innerHTML += html;
}
displaydetails(document.getElementById("detailslist"), details);
2
Answers
You might add an
onclick
handler to each button, which calls global function, passing the element, and then get the id:handler:
Or you can just pass id as an argument, if you don’t need the element:
Then you can use that id to search elements in the array by that id.
Instead of assigning clicks to each
<button>
, assign only one click listener to the parent and use Event delegation (which is also super useful if you add LI elements dynamically at a later time).Store the user ID in the button’s
data-*
attribute like =data-userid="${user.id}"
and retrieve it in JS usingElement.dataset.userid
. Once you have the ID, use Array.prototype.find to search for that Object in your users (details
) Array