So I have a JSON file I need to get Quiz questions from. For now, I am simply storing the questions in an array as an object. Each question object has 'text' (the question itself), 'choices' (an array of possible answers), and 'answer' (an int corresponding to the location of the correct answer choice).
How can I check that I'm storing the question objects correctly? I want to create a list of questions and I tried populating my list with questions[i].text and it didn't work. I installed Firebug to debug what was going on, but I am not entirely sure how to make the best use of it.
The JSON is in this format:
{
"text": "What does the author least like about Eclipse?",
"choices": [
"The plugin architecture.",
"FindBugs.",
"Refactoring.",
"The Run As menu."],
"answer": 3
}
My JavaScript file:
$(document).ready(function(){
var questions=[];
$.getJSON('quiz.js',function(data){
var i=0;
for(i=0;i<data.length;i++){
questions[i]=[String(data[i].text),String(data[i].choices),int(data[i].answer)];
}
var list = $('#list')
$(questions).each(function(_, text) {
var item = $('<li/>')
var link = $('<a/>').html(text)
link.click(function() { alert(text) })
item.append(link)
list.append(item)
})
$('#list').listview('refresh')
});
})
Finally, some HTML:
<div data-role="content">
<ul id="list" data-role="listview">
</ul>
</div>
I know it's a long question but I really appreciate any help. The end goal is to have a list of questions that, when clicked, displays the answer choices and provides a toast to notify the user if the selected option is correct or not. I also want to highlight the question in the list in Green if answered correctly, and Red otherwise.
EDIT:
Working code:
$(document).ready(function(){
$.getJSON('quiz.js',function(data){
var questions = data;
var list = $('#list')
$(questions).each(function(index, object) {
$.each(object, function(key, value){
if(key === 'text'){
//do something with qustion
var item = $('<li/>')
var link = $('<a/>').html(value)
link.click(function() { alert(value) })
item.append(link)
list.append(item)
$('#list').listview('refresh')
}
});
});
});
});
you're using each
wrong for one. Number two you have to realize that you're getting an Object of Objects back in your JSON response. You need to iterate over each object that contains your question/answer data and further iterate over that question/answer object. Further you have an array nested in that nested Object and need to loop through that to get your questions. Take a look at some pseudo code:
//will give you each object your data
$.each(data, function(key, object){
//do something with my [Object, Object]
$.each(object, function(key, value){
if(key === 'text'){
//do something with qustion
}
if(key === 'choices'){
//loop over array
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With