Looping through JSON data one at a time - javascript

I have the following test app: http://dev.driz.co.uk/quiztest/
The idea is that a series of webpages will each have a div that has the section number of quiz page e.g. 1 and then pull out the questions from a JSON file for that section.
This part I have working thanks to help from the SO community, so for clarity I have created a new question to deal with these issues which are separate.
The problem I have is that I only want the FIRST question to appear from a section on page load, and then when the user clicks on either the A or B button it then needs to load in the next question, so show question 2, and then 3 and so on...
Only one question at a time will be in the #questions ul for the user to answer.
Once all the questions for a section have been displayed I then need to do a callback to the finished function so that I can do some extra logic.
How do I best go about doing this? I'm thinking I'd need to first count the number of questions in the section and then do an increment to find the end. Can anyone help?
Edit: I'm planning on doing something like: Question 3 / 10 so getting that number is quite important it would seem. But I'm confused about getting the next question after the first and so and so on until then end of the section...
Thanks

I mocked what that website is in a fiddle. I don't know if this is exactly what you are looking for. Maybe with more explanation I could get it closer. Fiddle

Let's assume you have an array that contains your questions. Each question is an object, with a question key and an answers key. The question will always be a string that contains the text for the question. The answers will be an array with 0 or more elements of any type which signify the selectable answers to the question.
var questions = [
{question : 'What is 2 + 2?', answers : [4, 5, 6]},
{question : 'What is 6 * 4?', answers : [20, 24, 28]}
];
Now let's write a function to display a question. We'll use a global variable that stores the index of the question to be displayed (initialised to 0 to show the first question):
var currentQuestion = 0;
function displayQuestion() {
if(currentQuestion < questions.length) { // if there's still questions to display
var question = questions[currentQuestion]; // get the question to display
var questionHtml = ...; // generate the HTML for the question here
$('#questions').html(questionHtml);
currentQuestion += 1; // increase tracking index
}
else {
finished();
}
}
Then all you need to do is bind click event handlers to your buttons to call that displayQuestion() function.

Related

I need to programatically create several variables in javascript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I asked this question but it was marked as duplicate - it's not.
I need to programmatically create X number of variables (the number will be the value of someArray.length - which is also something created programmatically and thus unknown to me).
Is there any way to say "there's 8 items in this set, so I need 8 variables, and I need to be able to call on them/manipulate them later?" Hopefully I'm making sense.
My core problem: I programmatically generate a list of links. Can be any number of links. I need to be able to validate that the user clicks each of these links before advancing.
I programmatically generate a list of links. Can be any number of links. I need to be able to validate that the user clicks each of these links before advancing.
You do not need to create an unknown number of variables to solve your problem (how would you name them?). As stated by other commenters, you have a list of links, and you need to keep track of which ones have been clicked.
There are numerous ways to solve this problem in JavaScript. Below is an example of a straightforward approach which should be easy to follow. The approach is simply to use another array, linksClicked, to keep track of which links have been clicked. To validate, count the number of links that have been clicked and compare to the total number of links.
var arrayOfLinks = [
'http://www.stackoverflow.com',
'http://www.arstechnica.com'
];
var linksClicked = [];
function clickLink(url){
//check if link is in arrayOfLinks
for(var i = 0; i < arrayOfLinks.length; i++){
//if link is in arrayOfLinks, mark it as clicked
if(arrayOfLinks[i] === url){
linksClicked[i] = true;
}
}
}
function checkLinksClicked(){
//count number of links that have been clicked
var linkSum = 0;
for(var i = 0; i < linksClicked.length; i++){
if(linksClicked[i]){
linkSum++;
}
}
return linkSum;
}
console.log(checkLinksClicked());
clickLink('http://www.stackoverflow.com');
console.log(checkLinksClicked());
clickLink('http://www.stackoverflow.com');
console.log(checkLinksClicked());
clickLink('http://www.arstechnica.com');
console.log(checkLinksClicked());

jQuery count amount of divs on a page and hide? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm displaying an amount of divs on a page that can be anywhere from 1-50, all will be generated and loaded into the HTML via PHP, but I want to only display 9 initially and then load an additional 9 on a button click until all are loaded.
var alldivs = $('.preview-container').hide();
$('button').on('click', function(){
var turn = alldivs.splice(0, 9);
if (turn.length) {
console.log(turn);
turn.fadeIn();
}
});
Your question is very vague. For a better reference, you need to post your current code, what precisely you need to do and what you have searched so far. So it can help you to receive a better answer. But most likely you are looking for something like this:
$('li').click(function() {
var which = $(this).index();
$('div').find('div').hide().eq(which).show();
});
This is the shortest code I can think to do this:
var alldivs = $('div'); // select the elements you want to show here
$('button').on('click', function(){
var turn = alldivs.splice(0, 9);
if (turn.length) {
turn.fadeIn();
}
});
As the jQuery-selector returns an array with the matched elements you can combine that with the Array splice method to do what you want.
Basically alldivs.splice(0, 9) remove nine items starting at position zero from alldivs and returns the removed items.
Hope it helps.

JavaScript: Logic to display unknown number of tiles [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I have a situation where I get 4, 5 or 6 images/tiles.
Depending on the number of tiles, I need to format the images on the webpage.
Like this http://prntscr.com/9y75dw
If it's five images, I have to format it in such a way that two images in the first row and three images in the second row. Can you help me with the logic?
Well I don't see a technique, maybe I am missing to do that more appropriately or in a generic way but since the description in less and number of images given are random, I don't know how this will work.
var imageLength = $('img').length;
var newLength = 0, differenceLength=0;
if(imageLength%2==0){
//incase of even number
//Do what you like here eg: $('img').css('width', '50%');
}
else{
// incase of odd number
newLength = Math.round(imageLength/2); //dividing number into two parts.
differenceLength = imageLength - newLength; //difference to put smaller above and greater below.
$('parent-div img:nth-child(1)').nextUntil('img:nth-child('+differenceLength+')').wrapAll('<div></div>') //wraps into a container div
}
Although this is just one way. You might have already realized a lot of logic by now.
PS: I have randomly written this code so take it as a logic for help. Not sure whether this will work.

Javascript multipying without using * sign [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Practice Problem 1
Parameters: The function accepts two positive integers N and M.
Return Value: The function returns the product of N and M. For example, if the integers 5 and 8 are supplied to
that function, it should return the product of 5 and 8—it should return 40.
Additional
Requirements:
Do this without using the multiplication operator (*). Hint: Multiplication is just a series of addition
operations.
function mult(N, M) {
return N / (1 / M);
}
Since this is a basic excercise, I think that this answer is not expected (but maybe you'll get bonus points if you can explain it), even though it does the math without *.
function mult(N,M){
var a = new Array(N);
return a.join(""+M).split("").reduce((x,y)=>(parseInt(x)+parseInt(y)))+M
}
Note: This does not work for N < 3. No time to correct it.
OK. Look. It sounds like you're quite young so I think giving you the benefit of the doubt is alright here. So you know for the future: Stackoverflow isn't a site that you can just drop a homework question and expect people to do the work for you.
We sometimes do help with homework questions but only if it looks like you've at least attempted to answer the question yourself, by showing us some code that you've written. If you want to use SO in the future you might find the help section useful, particularly the section on how to write a good question.
OK, lecture over.
What the question is asking about is how to use a simple for loop to add some numbers together:
function getProduct(num1, num2) {
// set total to zero
// we'll be adding to this number in the loop
var total = 0;
// i is the index, l is the number of times we
// iterate over the loop, in this case 8 (num2)
for (var i = 0, l = num2; i < l; i++) {
// for each loop iteration, add 5 to the total
total += num1;
}
// finally return the total
return total;
}
getProduct(5, 8); // 40

How to make a javascript count up, such as world population? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I don't know how to make a Javascript count up that is related to the real time, which means when you reload the page, the counter won't start over again. Would anybody tell me how to make that happen :) Example like http://www.worldometers.info/ Thanks a lot.
The code they are using is likely pulling from a database with an actual value increasing live.
Check out this js fiddle I made for an example of how a simple timer can work. Notice that if you press "Run" multiple times, the time itself will stay constant.
Using a remote database will cause a lot more work, but for saving values across browser refreshes you should learn about localStorage I'd check out W3 School's article on the subject.
In my implementation I use
localStorage.setItem("time", currentTime); // Note that CurrentTime must be a string!
in each iteration of your code after setting the currentTime var.
When you start up your application, a simple if statement
if (localStorage.getItem("time") {
CurrentTime = localStorage.getItem("time");
} else {
// set default values
}
will work, as localStorage.getItem will return null if the value doesn't exist (or if you set the value to null manually).
(for localStorage, you can also use [bracket notation] and will probably see that in most common examples)
localStorage["foo"] = "value";
// is the same as:
localStorage.setItem("foo", "value")
// and
var bar = localStorage["foo"];
// is the same as:
var bar = localStorage.getItem("foo");

Categories