Exploring ways to improve the organization of homework code using arrays and loops after it has already been graded, aiming to enhance and refine it

I'm trying to optimize my code which currently consists of 10 variables and 10 functions. Each function is responsible for retrieving a specific variable and displaying it on an HTML page when a button is clicked. I want to use JavaScript to store the variables in an array and then create a loop to determine which button was clicked and retrieve the corresponding answer.

Although I am new to JavaScript, I believe creating an array is as simple as:

var names = ["var0", "var1", "var2"...];

The initial code I have looks like this:

var ans0 = "echo";
var ans1 = "candle";
var ans2 = "map";
var ans3 = "the letter r";
function answer0(){
    document.getElementById("question1").innerHTML = ans1;
}
function answer1(){
    document.getElementById("question2").innerHTML = ans2;
}
function answer2(){
    document.getElementById("question3").innerHTML = ans3;
}
function answer3(){
    document.getElementById("question4").innerHTML = ans4;
}

I know this approach can work, I just need some assistance with the syntax and logic.

In addition to that, here is a snippet of my HTML code:

<div class="questions">
                <p class="question">1. I speak without a mouth and hear without ears. I have nobody, but come alive with wind. What am I?</p><!-- echo -->
                <div class="answer-btn">
                    <input type="button" class="get" value="Answer" onclick="answer(0);">           
                </div><!--/.answer-btn -->          
                <span class="the-answer" id="question1"></span>     
            </div><!--/.questions -->

These lines are repeated multiple times throughout my codebase, so finding a more efficient solution would be ideal.

Answer №1

Instead of storing answers in separate variables, you can utilize an object to associate your answers with specific questions. To simplify the process, consider implementing the following approach:


var solutions = ['solution1', 'solution2', 'solution3', 'etc'];

function displayAnswer(questionNum) {
  document.getElementById('question'+questionNum).innerHTML = solutions[questionNum-1];
}

Make sure to call displayAnswer(1) to retrieve the answer for the first question.

Answer №2

If you want to simplify your code, consider adding a parameter to your function:

function displayAnswer(index) {
  document.getElementById("question" + index).innerHTML= solutions[index]
}

The array of all possible answers would be:

var solutions = ["echo","candle","map","the letter r"]

You can then either assign listeners to each button in your HTML like this:

<button class="ans_btn" onclick="displayAnswer(0)"></button>
 <button class="ans_btn" onclick="displayAnswer(1)"></button>
 ....

Alternatively, loop through the buttons and set up the event listeners:

var buttons = document.getElementsByClassName("ans_btn")
for(let j = 0; j < buttons.length; j++) {
  buttons.item(j).addEventListener('click', function()  {
    displayAnswer(j)
  })
}

Note that it is important to use let to correctly bind the index value. Otherwise, utilize a closure approach as an alternative:

var buttons = document.getElementsByClassName("ans_btn")
for(var j = 0; j < buttons.length; j++) {
  buttons.item(j).addEventListener('click', (function(j) {
    return function() { displayAnswer(j) }
  }(j)))
}

Edit: To simplify your HTML structure and avoid repetition, consider dynamically generating elements with JavaScript. Start by creating a container for your questions and answers:

<div id="q_a_container"></div>

In JavaScript, reference the container and store the questions in an array:

var qaContainer = document.getElementById("q_a_container")
var questionsList = ["1. ...... ?", "2. ........ ?", ...]

Loop through the questions array and append them to the DOM:

for(var qIndex in questionsList) {
   qaContainer.innerHTML += 
   '<p class="query">' + questionsList[qIndex] + '</p>\
      <div class="a-btn">\
         <input type="button" class="getAns" value="Answer" onclick="displayAnswer(' + qIndex + ');"> \          
      </div>\
      <span class="answer" id="question' + (parseInt(qIndex)+1) + ' "</span>'
}

I hope this explanation helps!

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

Approach for fetching these JSON records

I am currently exploring ways to retrieve all entries within a JSON payload using JavaScript. Specifically, I am interested in finding the best method to extract all instances of "o4" in a specific order (-159, -257). How can this be achieved? { ...

Validation of React Input for empty values or numbers

Looking for assistance with improving my method for checking the state of the calculator input and determining if it is empty or not. Here are the two issues I need help with: Is there a more elegant solution to incorporate a validation check to ensure ...

Groupings / BespokeItems

I'm struggling to build an array with headers based on a condition, with the desired output looking something like this: $array = @() $list = "" | Select Name,Value,Status foreach ($row in $worksheet) { $row.Psobject.Properties | ? { if ($RuleA ...

What is preventing my function from retrieving data from the JSON File?

Exploring the realm of JSON file manipulation, I am delving into how it functions. Equipped with a JSON file attached to my document and a function sharing the same name as my object in the JSON file. However, despite all efforts, the data is not being dis ...

Using JavaScript to set attribute values in Python Selenium, these values are cleared after each update

Assuming : for i in list('{}'.format(value)): self.browser.execute_script( "arguments[0].setAttribute('value', '{}');".format(i.replace('&b ...

Tips for adjusting the positioning of a div element in a responsive design

I am currently working on my website and facing a layout issue. In desktop mode, there is a sidebar, but in mobile view, the sidebar goes down under the content displayed on the left side. I would like the sidebar to appear at the top in mobile view, fol ...

Issue encountered with create-next-app during server launch

Encountering an error when attempting to boot immediately after using create-next-app. Opted for typescript with eslint, but still facing issues. Attempted without typescript, updated create-next-app, and reinstalled dependencies - unfortunately, the prob ...

The Azure SpeechSynthesizer encountered an error due to using HTTP instead of the expected HTTPS protocol. This issue can be resolved by installing the NPM package `microsoft

Recently, I have been encountering an issue with the microsoft-congnitiveservices-speech-sdk npm package. Everything was working smoothly until randomly an error started popping up. This could be due to a browser update or a minor package update - I'm ...

Tips for successfully transferring an image through an XMLHttpRequest

I found this helpful resource at: I decided to test out the second block of code. When I made changes in the handleForm function, it looked like this: function handleForm(e) { e.preventDefault(); var data = new FormData(); f ...

Tips on incorporating the source path from a JSON file into a Vue component

Is there a way to render images if the path is retrieved from a JSON file? Typically, I use require('../assets/img/item-image.png'). However, I'm uncertain how to handle it in this scenario. Component: <div v-for="(item, index) in i ...

Angular applications with separate, autonomous routers

Imagine having a massive enterprise application divided into multiple independent submodules (not to be confused with angular modules). I prefer not to overwhelm the routing in a single location and wish for these autonomous modules (non-angular modules) ...

Include an extra element in a list of items within a model class array

I have a data class @Parcelize data class PublicationPageModel( @SerializedName("pageNumber") val pageNumber: Int, @SerializedName("content") val content: String ): Parcelable I've already populated the array with ...

Reorganize code in JavaScript and TypeScript files using VSCode

Is there a way to efficiently organize the code within a .js / .ts file using Vscode? Specifically, when working inside a Class, my goal is to have static variables at the top, followed by variables, then methods, and so on automatically. I did some resea ...

Restrict form submission when minimum and maximum requirements are not met using JavaScript

I'm currently using JavaScript to show an error message when a user clicks on the form submit button and the entered number is not within the specified min and max range. The problem I am facing is that even when the submit button is clicked, the form ...

Ways to require text entry only when specific radio buttons are selected in jQuery

Currently, I am working on a project using JSP and have created an HTML form with a Process button at the top. When this button is clicked, a form is displayed containing two radio buttons - TestClient and TestServer. The form also includes a Submit butto ...

Discovering the power of Next.js Dynamic Import for handling multiple exportsI hope this

When it comes to dynamic imports, Next.js suggests using the following syntax: const DynamicComponent = dynamic(() => import('../components/hello')) However, I prefer to import all exports from a file like this: import * as SectionComponents ...

Google Maps Circle Radius Functionality Malfunctioning

I've been trying to implement a map scaling feature using a slider in my code but I'm having trouble getting it to work. While the map is displaying correctly, the radius won't update as intended. Any assistance with this would be greatly ap ...

Issue: Having trouble making the frontend work properly due to difficulty in accessing the 'state' property which is undefined

Encountering an issue while attempting to input data from a web application into the database. Having trouble understanding the root cause of the problem. The error occurs when the database insert button is triggered. The following snippets of code showcas ...

Signing up for event using react leaflet

I've been working on integrating React-Leaflet into my Create React App. I've successfully overlaid GeoJSON data on a base map, but I'm struggling to register clicks on this layer. While troubleshooting this problem, I came across a helpful ...

Leveraging deferred for linking loops involving several ajax requests

Despite the fact that several questions have been answered on this topic, none of them seem to be effective in this particular scenario. function login(u,p) { console.log(1); return $.post(url, {u,p}); } function out() { console.log(3); //a f ...