I have some sample data like so:
var data = {
"section": {
"1": {
"question": [{
"id": "1a",
"num": "1",
"title": "test"
}, {
"id": "1b",
"num": "2",
"title": "test"
}]
},
"2": {
"question": [{
"id": "2a",
"num": "1",
"title": "test"
}, {
"id": "2b",
"num": "2",
"title": "test"
}]
}
}
}
Using this I’m attempting to count the number of questions. So for this sample of data that would be 4 questions in total…
The plan is to update a progress meter width using this data:
<div id="progress"><div id="bar"></div></div>
Here is the JS code I have started putting together:
var number = 0, numQuestions, total, width;
function updateProgress() {
number += 1;
numQuestions = data.question;
//total =
width = total / number;
$('#progress #bar').animate({'width':width});
}
To get the width I’m guessing that I’d need to add BOTH sections and questions together and divide it by the width of the progress bar and then set the width of the progress as the number of that number??
Can anyone give some help and point me in the right direction?
The main issues are:
- numQuestions is returning undefined, so obviously I’m doing it wrong
- I’m not sure how to work out the total… should this be the
#progress #barwidth calculated against the numQuestions? Or something else entirely?
I would recommend modifying your data structure as follows:
Unless you need to name the sections, there is no need to key them.
You can then grab the number of sections like so:
var numSections = data.sections.length;To get the total number of questions in all sections, you’ll need to create a loop:
Then, to update the progress bar you would:
You’ll want
#progressto have a set width, and#barto have a percentage based width ranging from0to100%.If you need to name the sections, you can count the number of questions like so:
You can see all of this working here: http://jsfiddle.net/wAGHS/1/