I am experiencing issues with my for loop not functioning correctly within my On-Click Event in Javascript

Hello, I'm facing a bit of an issue with a for loop inside an On-Click Event. It seems like the loop is only showing me the last value from the array. Can someone please lend a hand here?

Below is the code snippet where I have an array with 10 values. I've tried using both a for loop and a foreach loop, but they are giving me the same outcome:

function getArray(){<br>
for(var i=0;i<Array_Name.length;i++){<br>
document.getElementById("p2").innerHTML=Array_Name[i];  <br>
}}
<br>

<input type="submit" value="CalC" onclick="getArray()" />

My aim is to display all 10 values when the button is clicked. Any suggestions or solutions would be greatly appreciated.

Answer №1

Here is the solution

function getArray(){
  for(var i=0;i<Array_Name.length;i++){
    document.getElementById("p2").innerHTML+=Array_Name[i]
  }
}
<input type="submit" value="CalC" onclick="getArray()" />

Answer №2

Your loop isn't quite right - try this instead:

for (var i = 0; i < 10; i++) {
   document.getElementById("p2").innerHTML += Array_Name[i];
}

Answer №3

For each element, make sure to either add it to the content of document.getElementById("p2") or keep it stored in a temporary variable.

function extractArray()
{
    let newData = "";
    for(var j=0;j<Data_Array.length;j++) 
       newData += Data_Array[j]; 
    document.getElementById("p2").innerHTML = newData;
} 

Answer №4

Wrong loop syntax detected. Refer to the MDN documentation for proper guidance.

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

What steps do I need to take to ensure my TypeScript module in npm can be easily used in a

I recently developed a module that captures keypressed input on a document to detect events from a physical barcode reader acting as a keyboard. You can find the source code here: https://github.com/tii-bruno/physical-barcode-reader-observer The npm mod ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

What is the best way to connect the user-input data with text in a span element?

Recently, I've started learning Vue.js and I'm facing an issue with binding data from an input field to a span element. Instead of appending the data, it's showing me undefined Here is the code snippet: new Vue({ el: "#app", data: { ...

One opportunity to interact with the menu by clicking only once

I am encountering an issue with a menu div that starts off with opacity set to 0 and visibility hidden. The purpose is for this div to become visible when clicking on another div (a menu that sticks to the top of my page, toggle-able via click). Everythin ...

What is the most effective way to send a list of objects to a Controller

https://i.stack.imgur.com/oyi5v.png This form is for billing purposes. You can add the item name, quantity, and price multiple times to calculate the total amount. Once you click on submit, all the included items along with other parameters like bill nu ...

Encountered an error loading resource: server returned a 400 (Bad Request) status when using Angular with NodeJS

My Angular and NodeJS application with Express (v4.17.1) exposes a REST API like this: app.get('/myRestApi', function (req, res) { console.log('here you are ... '); res.end('success!\n'); }); The body of this API ...

evaluate individual methods within a stateless component with unit testing

I am working with a stateless component in React that I need to test. const Clock = () => { const formatSeconds = (totalSeconds) => { const seconds = totalSeconds % 60, minutes = Math.floor(totalSeconds / 60) return `${m ...

Exploring Node troubleshooting with WebPack and Feathers

Currently, I am part of a team working on a project that involves using Node, Webpack, TypeScript, and Express/Feathers. While my fellow developers are experienced in these technologies, I have limited experience with JavaScript mainly on the client-side a ...

HTML/JS Implementation: Back to Top Visual Element

- This website appears to be quite simple at first glance. However, I have encountered an issue where every time I scroll down and then click on the "About" menu option, it abruptly takes me back to the top of the page before displaying the section with a ...

Unable to establish connection with remote database server on Hostinger platform

I've been encountering this persistent error that I can't seem to resolve. I developed my project locally, utilizing a local database. Upon completion, I attempted to manually migrate my database to my hosting provider since it's relatively ...

Mastering jQuery prior to delving into JavaScript skills

Just a heads up – I'm not here to debate whether learning JavaScript should come before jQuery. I already know that jQuery is built on top of JavaScript, so it makes sense to learn JavaScript first. I have a background in HTML and CSS, but now I wa ...

Issues arise when using ng-repeat in conjunction with ng-click

I am facing some new challenges in my spa project with angularjs. This is the HTML snippet causing issues: <a ng-repeat="friend in chat.friendlist" ng-click="loadChat('{{friend.friend_username}}')" data-toggle="modal" data-target="#chat" d ...

Unable to call upon JavaScript code from an external file

Just starting out with Spring and JavaScript! I've put together a JSP file https://i.sstatic.net/XemJ5.png In my first.js, you'll find the following method: function firstmethod() { window.alert("Enter a New Number"); return true; } H ...

Problem with input field borders in Firefox when displayed within table cells

Demo When clicking on any cell in the table within the JSFiddle using Firefox, you may notice that the bottom and right borders are hidden. Is there a clever solution to overcome this issue? I have experimented with a few approaches but none of them work ...

"Enhance input functionality by updating the value of the text input or resizing the textbox

I've been facing a challenge with updating the value of my input type=text or textbox control text value using jQuery $(window).resize(function(){});. I am aware that the event is triggered because an alert pops up when I resize the browser. Additiona ...

Tips for creating an if statement that checks arrays for specific numbers and characters, and then returns a boolean outcome

I am developing a program that determines which cards the player receives and checks if it is a Royal Flush. Although I have implemented code to identify the Royal Flush, it is not functioning as expected. Here is the code snippet: { private Card [] ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Unexpected Issue with JavaScript Ajax (Using jQuery.post): The Promise State Turns to "Rejected"

Recently, I've been encountering some issues while trying to debug my jQuery.post() call. The responses I'm getting are quite puzzling and I'm at a loss on how to proceed next. If anyone has any suggestions or insights, I would greatly appre ...

What is the best way to retrieve access to my container/store from this main file?

As a beginner in React/Redux, I am facing an issue where everything works fine in Redux when testing it. However, I am struggling to integrate it into my actual application. I believe that I need to use connect(), but I am unsure of how or where to imple ...

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...