I'm following the Mad Lib tutorial on Dash, but I run into the following problem:
Whenever I run the following code, it should store all three of my inputs in the array answers, however, it doesn't store the last one. Whenever I output the answers array with showFinal, it outputs undefined where the third answer should be. Here is a jsfiddle, outputting the same problem.
Here's the Javascript:
// List of prompts for the user
var prompts = [
'Type your name',
'Type an adjective',
'Type a noun'
];
var answers = [];
// Keep track of current prompt we're on
var currentPrompt = 0;
// A function that will call the next prompt
var nextPrompt = function() {
// if there is a next prompt
if (currentPrompt < prompts.length) {
if (currentPrompt != 0) {
answers.push($('input').val());
}
// put first prompt in all html elements with class
$('.prompt').html(prompts[currentPrompt] + '<br><input type="text">');
// move the next prompt into variable currentPrompt
currentPrompt = currentPrompt + 1;
}
//or else if we're at the end of the array
else {
// put a new message into the html.
showFinal();
}
}
var showFinal = function() {
$('.prompt').html(answers[0]+ ' ' + answers[1] + ' ' + answers[2]);
}
// run nextPrompt function when button is clicked
$('button').click(function() {
nextPrompt();
});
// Show the first prompt as soon as js loads
nextPrompt();
showFinal(). The prompts are at limit on last answer and they skip over pushing answer, but user just typed it