The responses stored within the array should remain intact and not vanish

I am facing a challenge with a basic exercise I am working on. The exercise involves allowing visitors to ask a random question, and in return, they receive a random answer from an array.

I wish to retain the questions and their corresponding answers. I want the previous questions and answers to remain visible even after a new question is asked. Each new question and answer should appear below the previous ones (unless the visitor refreshes the page). Currently, the previous content disappears when a new question is asked. How can I achieve this, and where should I make the necessary code changes?

index.html:

<div id="title">
        <h1>Get to know the future of your life in a <span>highly reliable way*</span></h1>
        <h2>Ask your question below <i class="arrow down"></i> </h1>
    </div>

    <div id="mydiv">
        <input type="text" id="myinput" placeholder="What question do you want to ask?">
        <button id="button" type="mybutton">START THE PREDICTION</button>
        <div id="myprediction"></div>
    </div>

    <h3 id="legal">*We are not responsible for inaccurate predictions.</h3>

script.js:

let button = document.querySelector("button");
let input = document.querySelector("input");
let prediction = ["Things don't look great for you.", "Don't worry, things will turn out fine.", "We're unsure about this outcome. Take control and make it happen.", "Take action before it's too late.", "Sometimes you need a break, then you can handle this.", "This might not work out."];

function predictor() {
    if (input.value !== "") {
        let randomNumber = Math.floor(Math.random() * prediction.length);
        let currentPrediction = document.getElementById("myprediction").innerHTML;
        document.getElementById("myprediction").innerHTML = currentPrediction + "<br>" + prediction[randomNumber];
    }
}

button.addEventListener("click", predictor);

Answer №1

Your string inside the

<div id="mijnvoorspelling">
element remains unchanged because you keep overwriting it with ..innerHTML = "new answer". To solve this, you can use the += operator instead of =. The += operator appends the new string to the existing one.

An alternative approach would be to create an element using document.createElement(), set the question string as the innerHTML of that element, and insert the new element into the document using insertAdjacentElement. This method provides more flexibility in defining the output appearance and placement. In this scenario, I transformed your

<div id="mijnvoorspelling">
into a <ul> and included each new item as an <li> element.

By utilizing insertAdjacentElement, you can specify the insertion position of your element. Currently, it is set to 'afterbegin', which means after the opening <ul> tag—essentially at the top. Changing this to 'beforeend' would place the output at the bottom of the list.

let button = document.querySelector("button");
let input = document.querySelector("input");
let mijnVoorspellingen = document.getElementById("mijnvoorspelling");
let voorspelling = ["Not looking good for you.", "Don't worry, things will turn out fine.", "Neither success nor failure is immediately apparent. Take charge and go for it.", "Act on this before it's too late.", "Take a break, then tackle this.", "This won't work."];

function fortuneTeller() {
  if (input.value !== "") {
    let randomNumber = Math.floor(Math.random() * voorspelling.length);
    let result = `Question: ${input.value}.<br> Answer: ${voorspelling[randomNumber]}`; 
    let listItem = document.createElement('li');
    listItem.innerHTML = result;
    mijnVoorspellingen.insertAdjacentElement('afterbegin', listItem);
  }
}

button.addEventListener("click", fortuneTeller);
<div id="title">
  <h1>Discover your life path in a <span>highly reliable manner*</span></h1>
  <h2>Pose your question below <i class="arrow down"></i> </h1>
</div>

<div id="mydiv">
  <input type="text" id="myinput" placeholder="What question do you have?">
  <button id="button" type="mybutton">ACTIVATE THE FORTUNE TELLER</button>
  <ul id="myfortunes"></ul>
</div>

<h3 id="legal">*We are not liable for inaccurate predictions.</h3>

Answer №2

Could you clarify what you mean by saying "I want the questions and the answers that go with the question to stay"?

Take a look at the following function. This function appends both the questions and answers to the div.

function predictor() {

    if (input.value !== "") {
        let randomNumber = Math.floor(Math.random() * predictions.length);
        document.getElementById("myprediction").innerHTML += "<b>Question:</b> 
        "+input.value+"&nbsp&nbsp&nbsp <b>Answer:</b> "+predictions[randomNumber]+" 
        </br>";
    }

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Two events can be triggered with just one button press

Is there a way to trigger two functions with just one button click? I want the button to execute the check() function and open a popup window with a PHP script. I've tried different approaches but none have been successful. Can anyone assist me? < ...

Is there a way to dynamically update the target of a form using JavaScript?

My goal is to change the target of a form in order to open a new window. However, all redirections of this form use the same window except for one specific button. This button calls a custom JavaScript function that needs to change the default "_self" targ ...

Tips for showcasing information from the tmdb api by leveraging the value or data obtained from a separate api

I am currently working on a project that involves displaying movie data using the tmdb api. I receive the response from my own api which only includes the id of the tmdb movie. Here is an example of the response: [ { "id": 0, "tit ...

PhpStorm alerts users to potential issues with Object methods within Vue components when TypeScript is being utilized

When building Vue components with TypeScript (using the lang="ts" attribute in the script tag), there is a warning in PhpStorm (version 2021.2.2) that flags any methods from the native JavaScript Object as "Unresolved function or method". For exa ...

Unable to reach elements that have been loaded through ajax with jQuery

I am facing an issue where I cannot access content loaded via ajax for modification. Unfortunately, I do not have access to the js file responsible for the initial load. Therefore, I need to create a separate function to alter the content. The required mo ...

The <a href="#divtagid"> link is incapable of triggering the opening of the div tag when called from JavaScript

I need help with displaying the content of a div with the id "hello" in maindiv when clicking on the href "Click Here", but it's not working as expected. Here is the code I have: $(document).ready(function() { var newhtml = '<a href="#he ...

NextJS build problem causing all content to become static

As a newcomer to NextJS with prior experience in basic React apps, I recently attempted to deploy a CRUD NextJS app (utilizing prisma and mongoDB). Everything runs smoothly with npm run dev, but issues arise when transitioning to npm run build followed by ...

Iterating through HTML table data using a JQuery for each loop

Currently, I have an HTML table that is structured in the following way: <div class="timecard"> <h3>tommytest</h3> <table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;"> < ...

Unusually Elevated Frame Rates within Three.js

I just launched a new website yesterday, which is dedicated to live editing three.js examples. I noticed that whenever I make updates to the code or switch between different example files, the frame rate of the site jumps up to around 1000 f/s. You can fi ...

JQuery receives an enchanting response from the magic line

I could really use some assistance with this problem. I've managed to make some progress but now I'm stuck! Admittedly, my JQuery skills are not that great! Currently, I have a magic line set up where the .slide functionality is triggered by cli ...

Adjust the time increment dynamically within the dropdown menu

I have a challenge to make a dynamic dropdown field that adjusts based on the value of a previous input field. There is a dropdown for selecting length, with options like 30 min., 60 min., and 90 min.. Additionally, there are input fields for startTime and ...

What is the method for activating a hook after a state change in a functional component?

I'm currently working on a custom pagination hook that interacts with an API to fetch data similar to React Query. The concept is straightforward. I aim to invoke this hook whenever a specific state (referred to as cursor) undergoes a change. Below i ...

Using a dynamic image source in an Ionic 3 background

I am using ngFor to display a list of posts, each of which should have a unique background image. The getBackgroundStyle function is responsible for extracting the URL of the image from the post array. <div class="singlePost" *ngFor="let post of da ...

Ways to stop Angular from automatically scrolling to the center of the page

I am facing an issue with my angular 11 application. Whenever I navigate to a specific page, there is an automatic scroll down which I don't want. Please refer to the attachment (gif) and homepage.html below to understand the scenario. https://i.ssta ...

Guidelines for integrating deep links into a ReactJS Ionic Android application

I have recently converted my ReactJS project into an android project following a tutorial. Now, I have successfully created an APK file and would like to configure the app to open when a specific URL is clicked on a mobile browser. Any guidance on how to a ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Having difficulty accessing the 'makeCurrent' property of an undefined object in Angular mobile application

I have followed the steps outlined in the Angular mobile toolkit guide found at https://github.com/angular/mobile-toolkit/blob/master/guides/cli-setup.md My Node version is v4.4.3 NPM version is 2.15.1 The issue arises when I run the command $ ng serve, ...

Is it impossible to generate a string exceeding 0x1fffffe8 characters in JSON parsing operations?

I am currently dealing with a JSON file that contains data of size 914MB. I am using the fs-extra library to load the file and parse it, but encountering an error during parsing: cannot create a string longer than 0x1fffffe8 characters Here is the code ...

Is it acceptable to include multiple modules within a single JavaScript file?

One thing that I've noticed is that the AngularJS (*.js) files I've come across typically only have one module, and the module name doesn't always match the file name. I'm curious to know if it's possible to include multiple modul ...

How to switch the active tab using redirection

I am currently facing an issue with my code. The specific problem I am encountering involves setting an active tab after redirecting a user to the page "http://localhost/account#tab-verification". Below is a snippet of the code I am working with: <ul ...