skip to Main Content

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


  1. You might add an onclick handler to each button, which calls global function, passing the element, and then get the id:

      <div>  <button   id="${array[i].id}" onclick="getId(event, this)" > GET ID </button>  </div>
    

    handler:

    function getId(event, element) {
     
        event.preventDefault();
    
        console.log('id: ', element.id);
    }
    

    Or you can just pass id as an argument, if you don’t need the element:

    onclick="getId(event, '${array[i].id}')" 
    

    Then you can use that id to search elements in the array by that id.

      const arrEl = details.find(el=>el.id == element.id);
    
    function getId(event, element) {
     
        event.preventDefault();
     
      const arrEl = details.find(el=>el.id == element.id);
      
      console.log('id: ', element.id, 'narray element:', arrEl);  
    }
    
    
    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="${array[i].id}" onclick="getId(event, this)" > GET ID </button>  </div>
         
      
    
      </li>`;
            //update the html 
            html += itemTemplate
        }
        //Update the parent once
        parent.innerHTML += html;
    }
    
    displaydetails(document.getElementById("detailslist"), details);
    <ol id="detailslist"></ol>
    Login or Signup to reply.
  2. 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 using Element.dataset.userid. Once you have the ID, use Array.prototype.find to search for that Object in your users (details) Array

    // DOM utils:
    const el = (sel, par) => (par || document).querySelector(sel);
    const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);
    
    // Utils:
    const getItem = (arr, key, val) => arr.find(item => item[key] === val);
    
    // Task: Users: 
    const displayDetails = (elWrapper, users) => {
      const elsList = users.map((user) => elNew("LI", {
        innerHTML: `<h2>${user.department}</h2>
          <div>Name: ${user.name}</div><div>id: ${user.id}</div>
          <button data-userid="${user.id}" type="button">GET ID</button>`
      }));
      elWrapper.append(...elsList);
    };
    
    const elParent = el("#detailslist");
    const details = [
      { id: 0, department: "HR", name: "samy" },
      { id: 1, department: "Accounting", name: "william" },
      { id: 9, department: "Development", name: "S.O." },
    ];
    
    // Events (delegated):
    elParent.addEventListener("click", (evt) => {
      const elBtn = evt.target.closest("[data-userid]");
      if (!elBtn) return; // Do nothing, not our button.
      
      const user = getItem(details, "id", +elBtn.dataset.userid);
      if (user) { // If user is found...
        console.log(user); // send user to server
      }
    });
    
    // Init:
    displayDetails(elParent, details);
    <ul id="detailslist"></ul>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search