Guide on dynamically adding elements to an array in key value format

Struggling to create a dynamic JSON array that stores name, email ID, and password of users every time someone signs up? I managed to do it for one user, but now I'm stuck trying to create a loop and push elements into the array. Any advice on how to accomplish this?

var users = [];
document.getElementById("sub").addEventListener("click",function store(){
var newUser = {};
newUser.name = document.getElementById("nme").value;
newUser.emailId = document.getElementById("mail").value;
newUser.password = document.getElementById("pd").value;
users.push(newUser);
console.log("user", users);
  });

Answer №1

Change the order of the array name and then add the user to it using push.

var users = [];
document.getElementById("sub").addEventListener("click", function addUser(){
    var user = {};
    user.name = document.getElementById("nme").value;
    user.emailId = document.getElementById("mail").value;
    user.password = document.getElementById("pd").value;
    console.log("user", user);
    users.push(user);
});

Answer №2

If my understanding is correct, this code snippet should get the job done.

let users = [];
document.getElementById("sub").addEventListener("click", function saveUser(){
    let userObj = {};
    userObj.name = document.getElementById("nme").value;
    userObj.email = document.getElementById("mail").value;
    userObj.password = document.getElementById("pd").value;
    users.push(userObj);
    console.log("user object: ", userObj);
    console.log("users array: ", users);
});

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

Discovering an element within a shadow root using Selenium in conjunction with Java

Is there a way to retrieve the "Solve the challenge" button from within the shadow-root (closed) element? Here is what I've attempted so far: driver.findElement(By.xpath("//[@id=\"solver-button\"]")).click(); Unfortunately, the button canno ...

Is it possible to automatically update the database information through a PHP script and AJAX?

I'm currently utilizing this function to retrieve database rows via ajax. function ajax_search(){ $("#search_results").show(); var search_val=$("#search_term").val(); $.post("find.php", {search_term : search_val}, function(data){ if (data.length ...

Having issues with PHP integration with HTML, JavaScript/jQuery, and AJAX functionalities

My HTML registration form is supposed to be a "step by step" form, using JavaScript and Ajax to call PHP in order to send an email with the values entered into the inputs. However, yesterday it sent an email without those values and the directory update di ...

Using CSS and JavaScript to hide a div element

In my one-page website, I have a fixed side navigation bar within a div that is initially hidden using the display:none property. Is there a way to make this side nav appear when the user scrolls to a specific section of the page, like when reaching the # ...

Refreshing dropdown arrays in Codeigniter with set_value

I'm facing an issue with this code snippet: <?php for ( $i=1; $i<=9; $i++ ) : ?> <select name="codes[]"> <?php foreach ( $errors as $error ) : ?> <option value="<?=$error->code?>" <?=set_select( 'cod ...

Is there a way to seamlessly transition to a new scene or page in my project while still having the option to easily navigate back to the previous

This is just the beginning of a series of scenes that I have in mind. As I move on to scene 2, I realize that my current method of fading to black and loading a new html file is becoming monotonous. I am looking for a more creative approach where the user ...

Challenges arise when attempting to return an early resolution within promises in JavaScript

I have a function that determines further execution within itself and needs to use promises since it is asynchronous. An issue arises where the function continues execution even after resolving. Here's my code: function initializeApplication() { ...

The attribute 'constructor' is not found on the 'T' type

I'm currently working on a project using Next.js and TypeScript. I've come across an issue where TypeScript is giving me the error "Property 'constructor' does not exist on type 'T'" in my generic recursive function. Here&apo ...

Interact with Datatable by clicking on the table cell or any links within the cell

When I am working with the datatable, I want to be able to determine whether a click inside the table was made on a link or a cell. <td> Here is some text - <a href="mylink.html">mylink</a> </td> Here is how I initialize my da ...

Bootstrap 5 - centering "padding" both internally and externally within the accordion

Need help aligning three Boostrap 5 grids: Header outside of accordion Overview in accordion header Details in accordion body The accordion header has margins and padding on the left and right, and the collapse icon also occupies some space. I want the ...

Ways to refresh a nested form

I'm currently learning Ruby on Rails and working on developing a web application. The app consists of a classic model with Users who can create Posts. Another model called Online is used to display the posts on a common wall, and it has an associatio ...

Duplicate multiple "li" elements using jQuery and place them in a designated position within the ul element, rather than at the end

I am currently working on developing a dynamic pagination bar. This pagination bar will dynamically clone the "li" elements based on a number received from an external webservice. Here is the structure of my pagination element: <ul class="pagination"& ...

Exploring the Elements of Arrays in C#

I am looking to develop a property in C# that can either set or retrieve an individual element of an array. Currently, my implementation looks like this: private string[] myProperty; public string MyProperty[int idx] { get { if (myProperty ...

"Enhance your web development with Vue.js and Vue-chart.js for beautiful linear

I'm currently struggling to implement a linear gradient background on my Vue-chart.js line chart. Despite searching high and low, the documentation and examples available are not proving to be helpful. After importing the Line component from vue-char ...

Where can I find the complete specification for the Calendarific JSON format?

I am interested in utilizing the Calendarific API for calculating working days in different regions. While the JSON response is informative, I am unable to locate a comprehensive definition of the fields within the API. In particular, I am seeking detail ...

Top solution for efficiently capturing and storing user input in a React JS application: Event Handler

I've recently designed an input field for inputting details of items. In order to effectively capture and save the entered information, which of the following event handlers would be most suitable? onClick onChange onLoad onKeyPress ...

Display an asterisk or bullet point in text fields and labels to indicate that the user does not have permission to view

In my current project, I have a specific requirement that involves displaying an asterisk or bullet dot for fields which the user does not have view access to. My goal is to keep the labels visible but show them as read-only with the asterisk data. Furthe ...

What is the reason behind the absence of a removeRange() method in CopyOnWriteArrayList?

What is the reason behind having the removeRange method in the ArrayList but not in its concurrent sibling? The protected void removeRange(int fromIndex, toIndex) method. I was just curious about this discrepancy, although it's not essential and I ...

A step-by-step guide on retrieving or parsing JSON data with Python

I am looking to use Python to extract or reorganize JSON based on the first-level key. Consider the following JSON: [{ "system": "test111", "data": { "title": "SomeValue", "time": "2 ...