jquerygetjsontargettemplate-literalsdynamic-class-creation

Targeting Dynamic Div


I am having trouble targeting a specific div on click, currently when I click "currentTarget.id" the function returns all of the div objects within my JSON file instead of the one that was clicked.

I have tried a bunch of different solutions from targeting on the backend heroku server to targeting it locally on the client side but every attempt has been "Almost Solved" / 90% of the way there but never fully solved.

I think the problem occurs when trying to map the dynamic JSON values into the users cards and it is conflicting with the "currentTarget.id" code?

Because when I remove the map/reduce function I can target the divs individually but without the "map" & "return" code I am unable to display all of the required data that I need.

Thank you for your time, any help would be greatly appreciated.

Best, Steve.

//THIS IS THE CODE TO CREATE DYNAMIC CLASSES FOR INDUSTRY VALUES
const industry_class = {
    "Health": "health-badge",
    "Education": "education-badge",
    "Construction": "construction-badge",
    "Science": "science-badge"
};

//THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
var userJSON = 'https://mighty-oasis-08666.herokuapp.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 CARD
var userCard = populateUsers.map(({id, industry}) => {
    let cls = industry_class[industry.trim()] || "";
    return `
            <div class='col col-4 align-items-stretch user-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>`;
    }).join("");
    $('#user-grid').append(userCard)
    //THIS IS THE CODE TO APPLY DYNAMIC CLASSES TO INDUSTRY VALUES
    $userType.each(function() {
        var $this = jQuery(this);
        let industry = $this.text().trim();
        if (industry in industry_class) {
            $this.addClass(industry_class[industry]);
        }
    });
});



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

        //THIS IS THE CODE TO CREATE DYNAMIC CLASSES FOR INDUSTRY VALUES
        const industry_class = {
            "Health": "health-badge",
            "Education": "education-badge",
            "Construction": "construction-badge",
            "Science": "science-badge"
        };

        //THIS IS THE CODE TO REFERENCE EXTERNAL JSON FILE
        var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'

        //THIS IS THE CODE TO FETCH EXTERNAL JSON FILE
        $.getJSON(userJSON, function(populateUsers) {
            //THIS IS THE CODE TO TARGET SPECIFIC JSON OBJECT ID VALUE
            const selectedUserId = e.currentTarget.id;
            const selectedUserData = populateUsers.find(
            (user) => user.id === Number(selectedUserId));

        //THIS IS THE CODE TO POPULATE JSON DATA INTO TEMPLATE LITERAL MODAL CARD
        var userModal = populateUsers.map(({id, industry}) => {
            let cls = industry_class[industry.trim()] || "";
            return `
            <div class='col col-4 align-items-stretch user-container'>
                <div id="${id}" class="card user-card">
                    <div class="card-body">
                        <h6 class="industry-type title ${cls}">${industry}</h6>
                    </div>
                </div>
            </div>
        `;
        }).join("");
        //THIS IS THE CODE TO APPEND DIV TO MODAL
        $("#modal-content").append(userModal);
        //THIS IS THE CODE TO APPLY DYNAMIC CLASSES TO INDUSTRY VALUES
        $userType.each(function() {
            var $this = jQuery(this);
            let industry = $this.text().trim();
            if (industry in industry_class) {
                $this.addClass(industry_class[industry]);
            }
        });
    });
    $("#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("");
});
.health-badge {
    background-color: purple;
    color: green;
    height: 80px;
    width: 80px;
}
.science-badge {
    background-color: black;
    color: yellow;
    height: 80px;
    width: 80px;
}
.construction-badge {
    background-color: blue;
    color: white;
    height: 80px;
    width: 80px;
}
.education-badge {
    background-color: orangered;
    color: black;
    height: 80px;
    width: 80px;
}
<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="hybrid-strain-chronic" 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>


Solution

  • You can use .filter to filter your datas which is return from server and only get JSON Array where value of id is same . Also, id is unique so only one record we need to get that's why no need to use .each loop just access record using values[0] this contents data after filter then access all your fields using that .

    Demo Code :

    const industry_class = {
      "Health": "health-badge",
      "Education": "education-badge",
      "Construction": "construction-badge",
      "Science": "science-badge"
    };
    var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'
    $.getJSON(userJSON, function(populateUsers) {
      var userCard = populateUsers.map(({
        id,
        industry
      }) => {
        let cls = industry_class[industry.trim()] || "";
        return `
                <div class='col col-4 align-items-stretch user-container'>
                    <div id="${id}" class="card user-card">
                        <div class="card-body">
                            <h6 class="industry-type title ${cls}">${industry}</h6>
                        </div>
                    </div>
                </div>`;
      }).join("");
      $('#user-grid').append(userCard)
    });
    
    
    $("#user-grid").on("click", ".user-card", function(e) {
      var userJSON = 'https://mighty-oasis-08666.herokuapp.com/users'
      const selectedUserId = parseInt($(this).attr('id'));
      $.getJSON(userJSON, function(populateUsers) {
      //get only json where id matches
        var values = $(populateUsers)
          .filter(function(i, n) {
            return n.id === selectedUserId;
          });
        let cls = industry_class[values[0].industry.trim()] || "";
        //gte all dataas..
        $("#modal-content").append(`<div class='user-container'><div class="${cls}"><h6 class="industry-type title">${values[0].industry}</h6> <h5>${values[0].name}</h5> <h5>${values[0].username}</h5></div></div></div>`);
        $("#user-modal").modal({
          show: true
        });
      });
    });
    $("#user-modal").on("hidden.bs.modal", function() {
      $("#modal-content").html("");
    });
    .health-badge {
      background-color: purple;
      color: green;
      height: 80px;
      width: 80px;
    }
    
    .science-badge {
      background-color: black;
      color: yellow;
      height: 80px;
      width: 80px;
    }
    
    .construction-badge {
      background-color: blue;
      color: white;
      height: 80px;
      width: 80px;
    }
    
    .education-badge {
      background-color: orangered;
      color: black;
      height: 80px;
      width: 80px;
    }
    <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="hybrid-strain-chronic" 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>