Ozzy
Ozzy

Reputation: 115

Get object value through a click event after each loop

I'm running an each loop over a JSON file that fetches objects corresponding to a click event on a button(.region) and then conditioning with an if statement.

There's no problem doing so without the click event, using it and trying to get the object just outputs undefined.

How can I make this happen using the following:

Object:

var data = {
    "employees": [{
            "title": "Jay Rob",
            "region": "IL",
            "startDate": "2016-12-06"
        }, {
            "title": "John Doe",
            "region": "UK",
            startDate ": "2016-12-06"

        }
    ]
}

JS:

$(document).ready(function() {
    $(data.employees).each(function() {
            var date = "2016-12-06";
            var reg = "IL";

            if (this.startDate == date) {

                $('#emp-main').append('<div class="emp-box"><h2>' + this.title + '</h2><span>' + this.region + '</span>');
                // Works like it should!
            }

            $(".region").click(function() {
                    //an if statement here, taking the current object from the loop, comparing it to the variable region and startDate and outputting HTML. Would not work because of the scope.
                    if (data.employees.region == reg && data.employees.starDate == date) {
                        $('#emp-main').append('<div class="emp-box"><h2>' + this.title + '</h2><span>' + this.region + '</span>');
                        //returns undefined
                    });
            });

    });
});

Upvotes: 0

Views: 290

Answers (1)

Abdelrahman M. Allam
Abdelrahman M. Allam

Reputation: 922

You are accessing data.employees.region this will give you undefined for sure, since data.employees is array you need to specify the index you want to access first, use $.each will send one by one like so

  $(data.employees).each(function(i, employee) {
        // then access region 
     employee.region
 });

after all you will face that getting the last object on all the buttons click so you need to isolate the scope with IIFE

  $(data.employees).each(function(i, employee) {
        // here scope for $.each
        // will affect the $.click scope 
        // because they use the same variable 
        // and $.each ends but the scope still accessible by $.click function 
    (function(emp){
         $(".region").click(function() {
        // because the $.click will be called later 
        // can see what $.each scope last value 

        // to avoid clash with the outer scope of .each
        // passed to function IIFE
        // and this act as eval the value of the variable directly on
        // declare it

             emp.region


         });
    }(employee));
 });

Upvotes: 1

Related Questions