1

I have a dynamically generated "user grid" and a dynamically generated "user modal". The modal is triggered when a "user card" is clicked (this functionality is working great).

However, when clicking on a specific "user card"... it does not just load the selected user card info, but it loads all of the user data for all of the user cards...

Essentially, I would like to click the "Leanne Graham Card" and only display the "Leanne Graham Modal" content.

Have included the code below

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://captain-steve.github.io/demo/db.json'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function (populateUsers) {

  //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL USER GRID
  var userCard = populateUsers.reduce((acc, {id, name, username, email, phone, company,}) =>
        acc += `
      <div class='col col-4 align-items-stretch strain-container'>
        <div id="${id}" class="card user-card">
          <div class="card-body">
            <h2 class="title">${name}</h2>
            <h6 class="title">${username}</h6>
            <h6 class="title">${email}</h6>
            <h6 class="title">${phone}</h6>
            <h6 class="title">${company}</h6>
          </div>
        </div>
      </div>`
    , ``);
    $('#user-grid').append(userCard)
});


//THIS IS THE CODE TO RUN WHEN USER CARD IS CLICKED
$('#user-grid').on('click', '.user-card', function(e){

    //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
    var userJSON = 'https://captain-steve.github.io/demo/db.json'

    //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
    $.getJSON(userJSON + "?id=" + e.currentTarget.id, function (populateUserModal) {

        //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL MODAL
        var userModal = populateUserModal.reduce((acc, {id, name, username, email, phone, company,}) =>
            acc += `
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h2 class="title">${name}</h2>
                        <h6 class="title">${username}</h6>
                        <h6 class="title">${email}</h6>
                        <h6 class="title">${phone}</h6>
                        <h6 class="title">${company}</h6>
                    </div>
                </div>`
            , ``);
        $('#modal-content').append(userModal)
    });
    $('#user-modal').modal({show:true});
});

//THIS IS THE CODE TO CLEAR ALL THE JSON DATA WHEN MODAL IS CLOSED
$("#user-modal").on("hidden.bs.modal", function(){
    $("#modal-content").html("");
});
<!-- Scripts & Sheets -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!-- Modal -->
<div id="user-modal" class="user-modal modal fade" tabindex="-1" role="dialog" aria-labelledby="uder-card" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div id="modal-content">

        </div>
    </div>
</div>


<!-- User Grid -->
<div id="user-grid" class="row container fluid-container"></div>    

Any help would be greatly appreciated!

Thanks a lot, Steve.

2 Answers2

1

Event object contains currentTarget property which refers to clicked item. You can use it in order to extract clicked item id.

Then you just need find the user by id in json you got

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = "https://captain-steve.github.io/demo/db.json";
//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
window.$.getJSON(userJSON, function (populateUsers) {
  //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL USER GRID
  var userCard = populateUsers.reduce(
    (acc, { id, name, username, email, phone, company }) =>
      (acc += `
      <div class='col col-4 align-items-stretch strain-container'>
        <div id="${id}" class="card user-card">
          <div class="card-body">
            <h2 class="title">${name}</h2>
            <h6 class="title">${username}</h6>
            <h6 class="title">${email}</h6>
            <h6 class="title">${phone}</h6>
            <h6 class="title">${company}</h6>
          </div>
        </div>
      </div>`),
    ``
  );
  $("#user-grid").append(userCard);
});

//THIS IS THE CODE TO RUN WHEN USER CARD IS CLICKED
$("#user-grid").on("click", ".user-card", function (e) {
  //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
  var userJSON = "https://captain-steve.github.io/demo/db.json";
  //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
  $.getJSON(userJSON, function (users) {
    const selectedUserId = e.currentTarget.id;
    const selectedUserData = users.find(
      (user) => user.id === Number(selectedUserId)
    );

    //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL MODAL
    let userModal = `
      <div id="${selectedUserData.id}" class="card user-card">
          <div class="card-body">
              <h2 class="title">User not found</h2>
          </div>
      </div>`;

    if (selectedUserData) {
      userModal = `
              <div id="${selectedUserData.id}" class="card user-card">
                  <div class="card-body">
                      <h2 class="title">${selectedUserData.name}</h2>
                      <h6 class="title">${selectedUserData.username}</h6>
                      <h6 class="title">${selectedUserData.email}</h6>
                      <h6 class="title">${selectedUserData.phone}</h6>
                      <h6 class="title">${selectedUserData.company}</h6>
                  </div>
              </div>`;
    }
    $("#modal-content").append(userModal);
  });
  $("#user-modal").modal({ show: true });
});

//THIS IS THE CODE TO CLEAR ALL THE JSON DATA WHEN MODAL IS CLOSED
$("#user-modal").on("hidden.bs.modal", function () {
  $("#modal-content").html("");
});
<!DOCTYPE html>
<html>
  <head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app"></div>
    <link
      rel="stylesheet"
      href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"
      type="text/javascript"
    ></script>
    <script
      src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"
      integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"
      integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl"
      crossorigin="anonymous"
    ></script>

    <!-- Modal -->
    <div
      id="user-modal"
      class="user-modal modal fade"
      tabindex="-1"
      role="dialog"
      aria-labelledby="uder-card"
      aria-hidden="true"
    >
      <div class="modal-dialog modal-dialog-centered" role="document">
        <div id="modal-content"></div>
      </div>
    </div>

    <!-- User Grid -->
    <div id="user-grid" class="row container fluid-container"></div>
    <script src="src/index.js"></script>
  </body>
</html>
Oleksandr Sakun
  • 452
  • 4
  • 9
  • @CaptainSteve No problem! Let Ahmet will be the "winner")) – Oleksandr Sakun Jan 18 '21 at 21:49
  • When I updated the "MockEnd" JSON to my own hosted JSON, the current target id command stopped working? why is that / how do I fix it? – Captain Steve Jan 19 '21 at 15:36
  • Since your data hosted on github you cannot retrieve data from it "partially" by using query params or by id in url path (it was possible to do in the server you used previously because it was real server for serving JSON and appropriate logic were written there) – Oleksandr Sakun Jan 19 '21 at 20:17
  • I would suggest use `find` method on data retrieved from github and put it into HTML template you have. Should I provide code snippet? – Oleksandr Sakun Jan 19 '21 at 20:19
  • I would love that ❤️ – Captain Steve Jan 19 '21 at 23:04
  • Oleksandr!!!! Your are a Magical Code Wizard ‍♂️, I cannot believe you got this working without a Server!!! Absolutely Incredible and very much appreciated. I now see why using a server is a better approach because targeting specific IDs and Objects locally adds quite a bit of additional code and logic. So both answers are right here, this one is for targeting locally and the next one is for when referencing a server. Very nice job Fellas! – Captain Steve Jan 21 '21 at 13:33
0

As Oleksandr Sakun said event object contains currentTarget which it contains id of what you clicked.

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://jsonplaceholder.typicode.com/users'

//THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
$.getJSON(userJSON, function (populateUsers) {

  //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL USER GRID
  var userCard = populateUsers.reduce((acc, {id, name, username, email, phone, company,}) =>
        acc += `
      <div class='col col-4 align-items-stretch strain-container'>
        <div id="${id}" class="card user-card">
          <div class="card-body">
            <h2 class="title">${name}</h2>
            <h6 class="title">${username}</h6>
            <h6 class="title">${email}</h6>
            <h6 class="title">${phone}</h6>
            <h6 class="title">${company}</h6>
          </div>
        </div>
      </div>`
    , ``);
    $('#user-grid').append(userCard)
});


//THIS IS THE CODE TO RUN WHEN USER CARD IS CLICKED
$('#user-grid').on('click', '.user-card', function(e){

    //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
    var userJSON = 'https://jsonplaceholder.typicode.com/users'

    //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
    $.getJSON(userJSON + "?id=" + e.currentTarget.id, function (populateUserModal) {

        //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL MODALS
        var userModal = populateUserModal.reduce((acc, {id, name, username, email, phone, company,}) =>
            acc += `
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h2 class="title">${name}</h2>
                        <h6 class="title">${username}</h6>
                        <h6 class="title">${email}</h6>
                        <h6 class="title">${phone}</h6>
                        <h6 class="title">${company}</h6>
                    </div>
                </div>`
            , ``);
        $('#modal-content').append(userModal)
    });
    $('#user-modal').modal({show:true});
});

//THIS IS THE CODE TO CLEAR ALL THE JSON DATA WHEN MODAL IS CLOSED
$("#user-modal").on("hidden.bs.modal", function(){
    $("#modal-content").html("");
});
<!-- Scripts & Sheets -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<!-- Modal -->
<div id="user-modal" class="user-modal modal fade" tabindex="-1" role="dialog" aria-labelledby="uder-card" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div id="modal-content">

        </div>
    </div>
</div>


<!-- User Grid -->
<div id="user-grid" class="row container fluid-container"></div>    

https://jsonplaceholder.typicode.com/users has a query parameter id which you can supply from currentTarget.

AK-35
  • 559
  • 2
  • 9
  • 24
  • When I updated the "MockEnd" JSON to my own hosted JSON, the current target id command stopped working? why is that / how do I fix it? – Captain Steve Jan 19 '21 at 15:36
  • is your mockend on local server? if it is not can you send it to me – AK-35 Jan 20 '21 at 01:50
  • Yes, I was using JSON Placeholder: https://jsonplaceholder.typicode.com/users – Captain Steve Jan 20 '21 at 14:57
  • The more I dig into this, the more it seems that the code you two provided was accurate but the issue is that I do not have a server... does this sound accurate? like should this code be able to work without a server or no? – Captain Steve Jan 20 '21 at 14:59
  • @CaptainSteve Yes you need a server running in background. Did you try to read it directly from .json file that sits in your pc ? – AK-35 Jan 20 '21 at 15:36
  • Yes, I did, 1 - Is there a good way to target JSON objects & values without a Server? 2 - Is it better to just use a server to target specific ids and objects? 3 - If I go the server route, will targeting and query parameters be "out of the box" or will they have to be defined? – Captain Steve Jan 20 '21 at 16:56
  • @CaptainSteve Yeah the problem is if you were just using .json file from your pc you can't use query parameters since it is not a server it is just a json file. Maybe this link might help https://spin.atomicobject.com/2018/10/08/mock-api-json-server/ – AK-35 Jan 20 '21 at 17:05
  • Your a Rock Star! I will work on setting up a Server! thank you so much Ahment ❤️ – Captain Steve Jan 21 '21 at 12:59