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
});
});
});
});
$.eachloop, that will bind it multiple times to the same elementthis.titleis no longer within the scope when you bind your click event. Create a new variable:var that = this;and recall it in your click event:that.title. Else bind it to the window object.$.each()to loop over an array.$(...).each()is for looping over DOM elements that match the selector in$(...).