Expanding arrays with the push method in Javascript

I have set up a web form using HTML to collect user data. Once the user submits the form, I am using JavaScript to store this data in an array. Here is my current code:

function saveData(){
    var userName = document.getElementById('myName').value;

    var dataArray = ["dataOne"];
    dataArray.push("dataTwo");
    dataArray.push("dataThree");

    dataArray.push(userName);
}

THE PROBLEM: The data entered by the user gets saved at index 3 in the array, whereas I want each new user submission to be stored at the next available index (e.g., index 4, 5, and so on). Currently, every user input overrides the previous one. For example:

User 1 Submits:

[dataOne, dataTwo, dataThree, User 1 Input]

If User 2 Submits:

[dataOne, dataTwo, dataThree, User 2 Input]

As you can see, User 1's input has been replaced by User 2's input. I need each user's data to be stored separately.

If anyone has a solution, I would greatly appreciate it. Thank you!

Answer №1

The issue here is in the way you're handling the array within the function. Instead of redeclaring or overwriting it each time, consider implementing a solution like this:

var data = ["firstData"]; //\
data.push("secondData");   //>resulting in var data = ["firstData", "secondData", "thirdData"]
data.push("thirdData"); ///

function addData(){
    var newData =  document.getElementById('inputData').value;
    data.push(newData);
}

This approach ensures that each invocation of the function will append a new string to the existing array.

Furthermore, remember to use distinct names for functions and variables to avoid conflicts (both cannot be named data).

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 is the correct way to properly import a non-relative path in TypeScript?

Struggling with importing into my TypeScript class. // Issue arises here... import * as Foundation from 'foundation/foundation'; // Everything runs smoothly until the above import is added... export class HelloWorldScene { constructor() { ...

Integrate my API with HTML using J.Query/Ajax technology

Finally, after much effort, I have successfully created a JSON java API. My API design is simple and based on Interstellar movie details: { "title": "Interstellar", "release": "2014-11-05", "vote": 8, "overview": "Interstellar chronicl ...

Using Google Maps to generate a polyline from an array

I have an array filled with various coordinates and data entries. My goal is to create a polyline that connects all these coordinate points within the array. While I can successfully place markers and infowindows, I am encountering difficulty in generating ...

Resolving Uncaught ReferenceError: require is not defined - Learn the solution here!

While working on my electron app, I encountered the error message Uncaught ReferenceError: require is not defined This is the relevant section of my code: const remote = require('electron').remote var minimise = document.getElementById('mi ...

How can I declare CSS variables in Next.js components' module.css just like in global CSS?

When writing CSS in our global file, we often define variables and styles like this: :root{ --orange:#e67e22; --black:#333; --light-color:#777; --border:.1rem solid rgba(0,0,0,.2); --box-shadow:0 .5rem 1rem rgba(0,0,0,.1); } *{ mar ...

Could it be that express-session is not compatible with express 4.13?

I have followed the setup instructions for express-session as outlined in the documentation, but it seems that my cookie is not being created. According to the documentation, simply setting the request.session value should automatically set the cookie. How ...

Whenever a form is generated dynamically, it consistently encounters a 403 forbidden error when attempting to make a POST request

I am encountering an issue with editing text posts on my website. Whenever I click the edit button, a form is dynamically created to replace the div element. I have set up a POST api in Django to handle the submission of this form and edit the existing pos ...

What is the best way to retrieve a value from a button function in order to utilize it in AJAX requests and SQL queries?

Having an edit button that allows users to change category names. When the edit button is clicked, a pop-up alert appears with an input field. Users can type in the input field, press okay, and the value should update with the input. This is the current co ...

Retrieving the 'red' pixel data from the texture rendered with gl.texImage2D

My objective is to transfer a Float32array to my fragment shader using a texture in order to process the data within the shader and then send it back to JavaScript. Since the data is not in the form of an image, I opted to transmit it as 'gl.R32F&apos ...

Directly transfer image to Cloudinary without creating a local file

I have integrated jdenticon to create user avatars upon signup in a node/express app. When working locally, I follow these steps: Create identicon using jdenticon Save the file on my local machine Upload the local file to cloudinary Here is a snippet o ...

Decoding JSON object from the "string" using JSON.parse function

I am attempting to send a JSON string from a PHP controller to a twig template using the following method: $data['dist_result'] = json_encode($distribution_service->setDistribution($ids,$distribution)); $this->display('backend/shipmen ...

MySQL and AJAX work together seamlessly in one, yet encounter compatibility issues in the other

I am utilizing AJAX to send a "load call" to a PHP script that includes data to be inserted into a database. The script is structured in the following way: <?php $create_tables = " CREATE TABLE IF NOT EXISTS `user` ( `id` int(11) NOT NULL PRIMARY KEY ...

Error encountered in THREE.js due to the specific version being imported

At the beginning of my three.js project, I opted for version 0.118.0 and included the necessary imports as shown below. import * as THREE from 'https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf ...

Picking a specific field from an array depending on a filtered value

Hello everyone, I am a newcomer to Angular and the entire MEAN stack ecosystem. Currently, I have a MongoDB database collection structured like this: db.users({ username: "Test1", fname: "Bob", lname: "Saget", email: "<a href="/cdn ...

Guide to configuring environment variables with Script [Node.js]

Is there a way to set an environmental variable using a script in node.js? I have a script that gives me the deployed solidity contract address and I need to use it in my .env file (I am using the dotenv module). I have been trying to figure out a way to ...

Tips on preventing bugs when the geocoder returns an empty array while fetching the user's country (Rails 4/geocoder)

I am currently working on a daily deal Rails application. My goal is to show the user only deals from the country they are associated with, using the geocoder gem for location detection. I have concerns about what would happen if the geocoder fails to re ...

Initiating a file download using HTML

When I try to initiate a download by specifying the filename, instead of downloading, it opens in a new tab. The code snippet below shows what I am currently using. Additionally, I am working on Chrome Browser. <!DOCTYPE html> <html> < ...

Encountered the error "Unable to update state on unmounted component in React because of timeout"

Despite the abundance of information available online about this particular warning, I am still struggling to find a solution that applies to my specific scenario. Currently, I am developing an autosave feature for a form component where typing triggers a ...

Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error: Uncaught TypeError: Cannot read property 'unshift' of u ...

Tips on deactivating automatic email client-specific content (such as Gmail or Outlook) in your emails

I have inserted the following code => <span style="font-size:12px;"><b>Name:</b></span></font><font size="1"><span style="font-size:12px;">Pratik</span> However, when viewed in a browser (such as Outlook ...