Bryan Valencia
Bryan Valencia

Reputation: 43

How to iterate through an array of questions and store in an array of user input?



I'm having a problem trying to iterate through an array of questions properly when I try to write them to the document. The first block of code I have included below is essentially what I'm trying to achieve except I'd like to it without prompts. I created an array called question[] that stores 3 question strings right now. The for loop with prompt(question[i]) takes each question in question[] and prompts the user to answer it. It then pushes that value to another array I made called character[].

I've tried a couple different methods to get this done using the .append method, but to no avail unfortunately and I think I can pinpoint my pitfalls to a few different areas.
In the the last blocks of code, I attempted to append the questions from question[] onto the page, and to then have the document listen for the input value to be changed, or for the Enter (key 13) to be pressed. Also, let it be known that I have wrapped all of this in the following function:
$(document).ready(function(){...}

var question = [
    '<br> What is your name?',
    '<br> Are you man or woman?',
    '<br> What is your class?'
];   
var character = [];

//For Loop Using prompt()
for (i = 0; i < question.length; i++) {
     var input = prompt(question[i]);
     character.push(input);
     alert(character[i]);
}

//For Loop Attempting to Use HTML '<input>'
<input id="user-input" placeholder="Type Here"></input>

for (i = 0; i < question.length; i++) {
    $('#game-text').append(question[i]);
    $('#user-input').onchange = function() {
        var userInput = input.value;
        character.push(userInput);
    }
}

OR

for (i = 0; i < question.length; i++) {
    $('#game-text').append(question[i]);
    $(document).keypress(function(key){
    if(key.which === 13 && $('#user-input').is(':focus')) {
        var input = $('#user-input').val();
        character.push(input);
    }
})

Instead of getting the loop displaying one question at a time, I'll have the loop display all questions at once and I can't seem to get it take in user input either.
I'm really not sure how to approach or what exactly the knowledge I'm missing is as I can't seem to find an answer to this online.

Again, to summarize my question is this:
How can I ask a question from an array on the page itself, have the page wait for a response, store that response in another array then do that again until I've gone through the entire array?
Thank you so much for your time! I would very much appreciate the help!

Upvotes: 4

Views: 1555

Answers (2)

Gaurav Bhatt
Gaurav Bhatt

Reputation: 7

Since you want to get the questionnaire on the page itself (without prompts), you can use jQuery events to control the flash of questions on the main page and also record the answers sequentially in an array. Here's what you can do:

var question = [
  'What is your name?',
  'Are you man or woman?',
  'What is your class?'
];
var i = 0;
var ans = [];

$(document).ready(function() {
  $("#ques").html(question[i]);
});

$("#answer").click(function() {
  ans.push($("#ans").val());
  $("#ans").val("");
  i++;
  $("#ques").html(question[i]);
  $("#answered").html(JSON.stringify(ans));
  if (i == question.length) {
    $("#ans").hide();
    $("#answer").hide();
    $("#ques").html("You've answered all the questions!");
  }
});
<!DOCTYPE html>
<html>

  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  </head>

  <body>
    <div id="ques"></div>
    <input type="text" id="ans" placeholder="Your Answer">
    <button id="answer">Answer</button>
    <pre id="answered"></pre>
    <script src="script.js"></script>
  </body>
</html>

Upvotes: 1

Shidersz
Shidersz

Reputation: 17190

You could use a recursive approach, wrapping the logic to ask a question inside a function, and when this process is done, then call again this function with the next question. Please, note I have removed the alert dialogs and replaced they by the console.log() at the end of all the process just to clean the logic a bit.

var question = [
    '<br> What is your name?',
    '<br> Are you man or woman?',
    '<br> What is your class?'
];
var character = [];

const askQuestion = (idx) =>
{
    if (idx >= question.length)
    {
        console.log(character);
        return;
    }

    character.push(prompt(question[idx]));
    askQuestion(idx + 1);
}

askQuestion(0);

Upvotes: 1

Related Questions