Storing user input in an array with the use of JavaScript

Hey everyone, I'm new to JavaScript and have been struggling with a task that seems simple. I'm trying to store user input in an array and then display it in a specific div (eventually I want to create a table using the DOM and store the input there). However, the code below isn't working as expected. Any suggestions on how to fix it?

JavaScript

function submitInfo(){

var nameInput = document.getElementById("name").value;
var ageInput = document.getElementById("age").value;
var fsInput = document.getElementById("fightingStyle").value;
var weightInput = document.getElementById("weight").value;

myArray[0]=nameInput;
myArray[1]=ageInput;
myArray[2]=fsInput;
myArray[3]=weightInput;

for(var i = 0; i<myArray.lenght; i++){
document.getElementById("theResult").innerHTML=myArray[i];
}

}

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="inl2a.css" />
<script type="text/javascript" src="inl2a.js"></script>
<title>Inlämning 2a</title>
</head>
<body>

<div id="inputFields">
<h3>Submit your fighters information:</h3>

Name:<br><br>
<input id="name" type="text" /><br><br>
Age:<br><br>
<input id="age" type="text" /><br><br>
Fighting style:<br><br>
<input id="fightingStyle" type="text" /><br><br>
Weight:<br><br>
<input id="weight" type="text" /><br><br>

<input id="button" value="Submit" type="button" onclick="submitInfo();" /><br><br>
</div>

<div id="theResult">
</div>

</body>
</html>

Answer №1

function saveData(){
    var infoArray = []; // issue 1

    var name = document.getElementById("name").value;
    var age = document.getElementById("age").value;
    var style = document.getElementById("fightingStyle").value;
    var weight = document.getElementById("weight").value;

    infoArray[0] = name;
    infoArray[1] = age;
    infoArray[2] = style;
    infoArray[3] = weight;

    for(var i = 0; i<infoArray.length; i++){ // issue 3
        document.getElementById("output").innerHTML += infoArray[i]; // issue 2
    }

}
  1. The array is not being initialized before use
  2. Only the last value is displayed due to overwriting of innerHTML property
  3. A typo exists in the loop condition: "lenght" instead of "length"

You can streamline the code by directly pushing values into the array without using intermediate variables. Additionally, fetching the output element outside the loop can improve performance:

function saveData(){
    var infoArray = []; // issue 1

    infoArray.push(document.getElementById("name").value);
    infoArray.push(document.getElementById("age").value);
    infoArray.push(document.getElementById("fightingStyle").value);
    infoArray.push(document.getElementById("weight").value);

    var outputElement = document.getElementById("output");

    for(var i = 0; i<infoArray.length; i++){
        outputElement.innerHTML += infoArray[i]; // issue 2
    }

}

Answer №2

Assuming the user inputs are for a title and a name, you can store them in variables like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;

Instead of keeping them as separate variables, you can put them in an array like so:

var info = [ title, name ];

When you want to display the title, you can do it like this:

document.getElementById(your_divID).innerText=info[0];

For Mozilla support, you can use textContent instead of innerText.

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

Creating the document.ready function in Angular2 with JQuery

I am seeking assistance to modify the JQuery function so that it can run without the requirement of a button click. Currently, the function only executes when a button is clicked. Code declare var jQuery: any; @Component({ selector: 'home-component ...

Displaying Dates in an Express Application using EJS

I have a MySQL table with a column containing date data. I am building a webpage to display this data in a more user-friendly way. Currently, the displayed result looks like this: https://i.sstatic.net/lGamr.png I would like the dates in the column to ...

Creating a custom progress bar using Javascript and Jquery

I developed a progress bar that is fully functional. Here is the HTML structure: <div class="progress"> <div class="progress-bar progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style ...

Angular's separate scope variables allow for isolated data manipulation within individual components

Struggling with one scope variable affecting multiple elements in a div in AngularJS. Looking for help as a beginner in handling this issue. For a clearer understanding, here's an example: JS: /* controller-home.js ********************************* ...

Error: The process.binding feature is not supported in the current environment (browserify + selenium-webdriver)

Recently, I've been attempting to execute a Node.js code on the client side of my browser. To make my code compatible with browsers, I am using Browserify for conversion purposes. Below is the command I use for this transformation: browserify te ...

The login process in Next-auth is currently halted on the /api/auth/providers endpoint when attempting to log in with the

My Next-auth logIn() function appears to be stuck endlessly on /api/auth/providers, as shown in this image. It seems that the async authorize(credentials) part is not being executed at all, as none of the console.log statements are working. /pages/api/au ...

Reduce the transparency of the overlay picture

I have been utilizing the 'Big Picture' template to design a webpage. The overlay.png file adds a lighter background effect by overlaying intro.jpg with a partially transparent blue graphic. Despite my efforts to adjust the opacity and gradient/R ...

Is there a way to prevent redirection to the homepage after submitting a login form?

Having trouble with my Single Page application: every time I refresh the page after rendering the login form, it goes back to the homepage. How can I prevent this and make sure the page stays on the login form even after a refresh? This is what my homepag ...

Encountered an error when attempting to access property 'connect' of an undefined value

I encountered an issue with pg.connect not being defined in the Handler module. My goal is to set up a table using postgres in fastify. In my routes handling folder, I manage the routes and send API requests. The error occurs when I navigate to http://loc ...

Looping through a jQuery script to add a class if a certain condition is met in another class

$(document).ready(function() { if ($("#grid .media-box").hasClass("brand1")) { $("#grid .media-box-content").addClass("brand01") }; } }); and in body looping div grid <div id="grid"> <?php foreach($data as $items) { ?> <div cl ...

Using jQuery to load and parse a JSON file stored on a local system

I am a beginner in scripting languages and recently searched for ways to load and parse JSON files using jQuery. I found helpful resources on Stack Overflow. The JSON file I am working with is called new.json. { "a": [ {"name":"avc"}, ...

Unexpected behavior in Next.js when using Auth0: pageProps are empty when wrapped with withPageAuthRequired HOC

Explaining the Issue The problem arises when using withPageAuthRequired with getServerSideProps, as the pageProps object is empty. Despite following common practices, the pageProps parameter remains undefined. Expected Outcome Upon calling getServerSideP ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

Utilize Angular 5 to implement URL routing by clicking a button, while also preserving the querystring parameters within the URL

I have a link that looks like this http://localhost:4200/cr/hearings?UserID=61644&AppID=15&AppGroupID=118&SelectedCaseID=13585783&SelectedRoleID=0 The router module is set up to display content based on the above URL structure { path: & ...

Despite using callbacks when passing props in React JS components, the rerendering still occurs

In my React project, I implemented callbacks to prevent excessive rerendering due to the large amount of data being displayed and numerous buttons that trigger these rerenderings when clicked by the user. The useCallback hooks are effective in preventing ...

Issue with Vue.js: Nested field array is triggering refresh with inaccurate information

I've been working on a Vue page where I want to have nested field collections, with a parent form and repeatable child forms. Everything seems to be working fine except that when I try to delete one of the child forms, the template starts rendering i ...

Encountering a SyntaxError with the message 'Unexpected token' while trying to require a module in strict mode from JSON at position 0

Within the index.js file, the following code is present: 'use strict'; const config = require('./config'); In the config.js file, the code looks like this: 'use strict'; const config = new function() { this.port = 3000; ...

What steps are involved in implementing an ordering system on a restaurant's website using React?

As I work on developing my portfolio using React, I'm interested in incorporating an online ordering feature. However, the information I have found through Google so far hasn't fully addressed my questions. Can anyone provide guidance on the best ...

Using jQuery to add a class to an input option if its value exists in an array

Looking for a way to dynamically add a class to select option values by comparing them with an array received from an ajax call. HTML <select id="my_id"> <option value="1">1</option> <option value="2">2</option> ...

Enable users to input their custom code and run it when the specified conditions are met

Currently, I am developing a Multi-tenant application that requires users to input their own code and run it under specific conditions. I have several ideas in mind, but I am unsure which approach would be most effective. All the proposed methods will ha ...