I am trying to create a simple flashcard game where a list of people's names in a JSON file is looped over (randomly) and then the user selects which is the correct person.
I have the selecting of person working, but I cannot seem to randomly loop over the JSON file. I have looked here and here but have not been able to get either to work.
Here is the JSFiddle: http://jsfiddle.net/pacj02xq/1/
HTML:
<div>
<h3>Who is this?</h3>
<div id="namesOutput"></div>
</div>
JavaScript (jQuery):
$(document).ready(function() {
var answers = 3;
//
// Retrieve JSON
//
$.getJSON("https://gist.githubusercontent.com/keenanpayne/ada118875c2a5c672cd3/raw/8a72fc99c71c911f497200a7db3cc07b2d98dc82/sample.json", function(result) {
var staffNumber = 0;
var correctAnswer = "";
var correctAnswerID = Math.floor((Math.random() * 3) + 1);
// Loop through set
$.each(result, function(i, field) {
staffNumber++;
if (staffNumber == correctAnswerID) {
correctAnswer = field.name;
}
// Output possible answers
$("#namesOutput").append('<a class="btn gameBtn" title="' + staffNumber + '">' + field.name + '</a>');
// Break loop depending on level
if (staffNumber === answers) {
return false;
}
});
//
// Check answer
//
$(".gameBtn").click(function(e) {
e.preventDefault();
if ($(this).attr('title') == correctAnswerID) {
$(this).addClass("btn--correct");
$('.btn').not(".btn--correct").addClass("btn--incorrect");
} else {
$(this).addClass("btn--incorrect");
}
});
});
});