I'm trying to collect user responses and add them into the answers array. Then I want to display the most recent user input (answers[0]
) into the .user-answer div
. I've managed to get that part taken care of but if you see a better way to do it then please show me.
The second part of is that I want to show the items in the array one at a time in the .dynamic-content h2
slot. I need to loop through the array (starting at answers[0]), pull out each item, show it in the div and then move to the next item and show it in the div
.
Here's a link to the CodePen.
HTML
<div class="answer">
<h1>Life, Liberty, and </h1>
</div>
<div class="user-answer">
<h1>_________</h1>
</div>
<input type="text"/>
<input type="submit"/>
<div class="dynamic-content">
<h1>What is your pursuit of happiness?</h1>
<h2>Output array items here</h2>
</div>
JavaScript
// create an empty array
var answers = [];
// STORE AND OUTPUT DATA ON SUBMISSION
function handleUserInput() {
// store user input
var userInput = $('input[type=text]').val();
// append input value to answers array
answers.unshift(userInput);
// add latest user input into the HTML
$('.user-answer').html('<h1>' + answers[0] + '</h1>');
}
// RUN FUNCTION ON SUBMISSION
$('input[type=submit]').on('click', function() {
handleUserInput();
});